ash1eygrace

Web developer, open source contributor, obsessed with systems, stationery, & Obsidian.

How to Check DOM nodeTypes & nodeNames

There are 12 different node types and each node may or may not have its own children of different node types. Node types can be thought of as communication protocols and essentially define how each node communicates with other nodes.

There’s no point in memorizing them all, and a good reference to keep on hand is the page HTML DOM Element nodeType from W3Schools.

nodeType

We can determine the type of a node by querying the DOM and using the nodeType property. In the example, bellow I’m grabbing the “Hey, I’m Ashley” on my front page:

const heyHeading = document.querySelector('.wp-block-cover__inner-container > h2 > strong > mark');
console.log(testing.nodeType);

Console logs 1 as the nodeType. Remember you can reference the nodeType list from W3Schools and see that node type 1 represents an Element.

nodeName

To get the node name, you can use the same const heyHeading but this time use the property nodeName like this:

const heyHeading = document.querySelector('.wp-block-cover__inner-container > h2 > strong > mark');
console.log(testing.nodeName);

You’ll see that it returns the node name MARK since the heading is nested inside an element named <mark>. Any node encased in <..> tags will be a node type 1, which is an element.

Here’s what we see in Console:

In addition to the above nodeName and nodeType properties, there are other properties you can use like .childNodes to return a list of all the children of a node, or .nextSibling that returns a node representing the next node in the tree.

You can learn more about nodes and find more properties from these additional resources:

Leave a Reply

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