Nodes vs Elements in the DOM

In my early JavaScript learning process, I came across two objects: ‘nodes’ and ‘elements’ which triggered some confusion in my mind. I thought both objects were the same, when in fact, it turns out they are not technically the same because there is a clear distinct difference between both. Let’s sort out that difference between nodes and elements.

What’s a node? it is the name of any type of object in the DOM tree. It could be one of the built-in DOM elements such as the document itself, document.head or document.body. A node could be an HTML tag specified in the HTML such as <input>, <div>,<h2>, <p> or it could be a comment node, text node… In fact, a node is any DOM object and every node has a parent, every node is allowed to have one or more children or even zero children.

What’s an element? An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id or a class. can have children, etc.

Nodes vs Elements: Nodes are all the different components that a webpage is made up of and elements are one type of node.

Let’s have a look on some types of node, their value and description

The following html element has two children: head (line 3) and body (line 10) and these are two ‘nodes’. The head and body are element nodes. Inside the body (line 12) there is a comment (navbar), it’s one children of the body and it’s a comment node

Since every node has properties, therefore let’s find out in the console the ones for element node ‘body’.

  1. .nodeName property has a return value “Body”
  2. .nodeType property returns a value of 1 which means that body is ELEMENT_NODE.
  3. .parentNode shows this element node “Body” has parentNode which is the html element.
  4. .children property returns HTML collection,
  5. .COMMENT_NODE has a return value of 8, which states that we have comment node as of the children of the body.

That’s all for this topic and thank you for reading this blog.

resources:

  1. https://www.youtube.com/watch?v=y3itGTCseAk
  2. https://stackoverflow.com/questions/9979172/difference-between-node-object-and-element-object#:~:text=So%2C%20in%20a%20nutshell%2C%20a,and%20a%20nextSibling%20and%20previousSibling.
  3. https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType

Full Stack Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store