What is the difference between $('this')[0].nodeName and $('this')[0].tagName?
Difference between .tagName and .nodeName
59.4k Views Asked by Kdniazi AtThere are 4 best solutions below
On
The tagName property is meant specifically for element nodes (type 1 nodes) to get the type of element.
There are several other types of nodes as well (comment, attribute, text, etc.). To get the name of any of the various node types, you can use the nodeName property.
When using nodeName against an element node, you'll get its tag name, so either could really be used, though you'll get better consistency between browsers when using nodeName.
On
Read about those properties in the DOM Core spec.
nodeName is a property defined in the Node interface
http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-F68D095
tagName is a property defined in the Element interface
http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-104682815
btw the Node interface is implemented by every node in the DOM tree (including the document object itself). The Element interface is implemented only by those nodes in the DOM tree that represent elements in an HTML document (nodes with nodeType === 1) .
On
And this is what happens on Firefox 33 and Chrome 38:
HTML:
<div class="a">a</div>
Js:
node = e
node.nodeType === 1
node.nodeName === 'DIV'
node.tagName === 'DIV'
node = e.getAttributeNode('class')
node.nodeType === 2
node.nodeName === 'class'
node.tagName === undefined
node = e.childNodes[0]
node.nodeType === 3
node.nodeName === '#text'
node.tagName === undefined
So:
- only use
nodeTypeto get the node type:nodeNamebreaks fornodeType === 1 - only use
tagNamefornodeType === 1
This is a pretty good explanation of the difference between the two.
Added text from the article: