šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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>
<html>
    <p>
        Welcome to my site!
    </p>
</html>

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *