Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Is there a difference between DOM Node and Element?

Driven by a strange curiosity I've spent some time reading why we have both the Node and Element notations, and if there is a difference between them. This is what I've discovered:

An HTML document is made of multiple nodes, organized as a tree structure, the DOM. For example:

<!DOCTYPE html>
        Welcome to my site!

In the above document, we have a total of 4 DOM nodes. We have the <!DOCTYPE>, the <html>, the <p> but also the text node Welcome to my site! is seen as a separate node.

Out of these 4 nodes, only 2 of them are Elements: the <p> the and <html>.

In short, an element is a particular type of node, and it is written using a tag in the HTML document.

The <!DOCTYPE> and Welcome to my site! are DOM Nodes, but are not Elements given that they are not represented by real tags.

In order to find out what is the type of a node type you can write:

const paragraph = document.querySelector('p');
paragraph.nodeType === Node.ELEMENT_NODE; // true

While if we select the text of a paragraph:

const paragraph = document.querySelector('p');
const firstChild = paragraph.childNodes[0];
firstChild.nodeType === Node.TEXT_NODE;  // true

Found a good article on this subject on Dmitri's Pavlutin site.

Home Screencasts Best of Newsletter Search X