Categories
JavaScript Answers

What’s the Difference Between the tagName and nodeName Property of a DOM Node in JavaScript?

Spread the love

In a DOM node object, we see the tagName and nodeName property when we inspect a DOM node object.

In this article, we’ll look at the difference between the tagName and nodeName property of a DOM node in JavaScript.

Difference Between the tagName and nodeName Property of a DOM Node in JavaScript

The tagName and nodeName property of a DOM node isn’t the same in most cases.

It’s only the same if the node is an element node.

For instance, if we have the following HTML:

<div class="a">a</div>

Then we can log the values of nodeName and tagName for each types of nodes by writing:

const div = document.querySelector('div')
console.log(div.nodeType)
console.log(div.nodeName)
console.log(div.tagName)

const attributeNode = div.getAttributeNode('class')
console.log(attributeNode.nodeType)
console.log(attributeNode.nodeName)
console.log(attributeNode.tagName)

const childNode = div.childNodes[0]
console.log(childNode.nodeType)
console.log(childNode.nodeName)
console.log(childNode.tagName)

div is an element node representing the div.

The console log logs the following values:

div.nodeType is 1.

div.nodeName and div.tagName are both 'DIV' .

attributeNode is an attribute node for the class attribute of the div.

attributeNode.nodeType is 2.

attributeNode.nodeName is 'class' and div.tagName is undefined .

childNode is a DOM node for the text content of the div.

childNode.nodeType is 3.

childNode.nodeName is '#text' since childNode is a text node and div.tagName is undefined .

Therefore, we can see that nodeName and tagName are only the same for elements.

Conclusion

For DOM elements, nodeName and tagName are both set to the tag name of the element as their values.

However, for non-element nodes, their values will be different.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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