Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to get an element's tag name in JS?

I want to get the name of a certain tag (to tell whether it is a div/input/span/p/so on)

I found that there are 3 different attributes that give me the tag name:

tagName, nodeName, and localName

My question is: Which one is the most supported in all browsers? And/or is there a method to get the tag name in Prototype (I looked but couldn't find one)?

like image 392
Mitch Dempsey Avatar asked May 01 '10 21:05

Mitch Dempsey


People also ask

How do I find the tag name of an element?

The tagName read-only property of the Element interface returns the tag name of the element on which it's called. For example, if the element is an <img> , its tagName property is "IMG" (for HTML documents; it may be cased differently for XML/XHTML documents).

What is tagName in JavaScript?

Definition and Usage. The tagName property returns the tag name of an element. The tagName property returns the tag name in UPPERCASE.


1 Answers

nodeName is the most consistent here. I would suggest you take a minute and read this post for a few differences and inconsistencies with tagName if you're more curious as to why.

For the prototype part of the question...it's a JavaScript property, just this.nodeName should work or element.nodeName, whatever your element's called in the current function should work.

like image 101
Nick Craver Avatar answered Sep 18 '22 11:09

Nick Craver