If you check an HTML element's nodeName and tagName properties, you'll get the same result. So... What's the difference?

The nodeName property

A Node isn't necessarily an Element, so the nodeName property won't always return an HTML tag name.

There are twelve different values the nodeName property can return, including #comment, #document, and #text.

You can find the full list in the MDN Web Docs.

The tagName property

The tagName property only works on a Node that is also an Element.

If you try to access it on a different type of node, you'll see undefined. If it isn't an HTML element, it doesn't have a tag name.

Trying it out

If you want to test this, first highlight an HTML element in the inspector. Then access it in the console using the $0 shorthand. Try accessing its nodeName and tagName properties like so:

  • $0.nodeName;
  • $0.tagName;

Then do the same thing with an HTML comment and notice the difference.

Wrapping up

The nodeName and tagName properties might have the same value, but this is purely coincidental.

I usually default to the tagName property unless I specifically need to check something that isn't an HTML element.