简体   繁体   中英

How to get the name of an element with Javascript?

I'm trying to get the name of an element in Javascript. Meaning if the element is <div /> , then "div" would be returned. If it's <img src="" /> then "img" would be returned. I'm using jquery to select a bunch of elements and then calling a custom function on all of them. Within that function I want to know what I'm dealing with. How do I do this?

Seems like a simple thing. And I think I've done it before but I just can't find it. Google results keep giving me "get element by name" no matter how I phrase it.

Use nodeName (see this note about tagName ):

"My advice is not to use tagName at all. nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice."

You want element.nodeName Or, within jQuery:

$(".includeMe").each(function(){
  alert(this.nodeName);
});

<img class="includeMe" src="puppies.jpg" />
<div class="includeMe">Hello World</div>
<p   class="includeMe">Don't forget me as well</p>
$(selector).each(function() {
    switch (this.tagName) {
        // Handle cases
    }
});

For element.tagName and element.nodeName return the name of your tag, in uppercase.

If you want it in lowercase, just use element.tagName.toLowerCase() or element.nodeName.toLowerCase() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM