最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - How to get the name of an element with Javascript? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Jan 1, 2010 at 21:33 Brian Campbell 333k59 gold badges366 silver badges342 bronze badges asked Jan 1, 2010 at 21:28 fentfent 18.2k16 gold badges90 silver badges91 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 11

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."

tagName or nodeName

$(selector).each(function() {
    switch (this.tagName) {
        // Handle cases
    }
});

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>

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().

发布评论

评论列表(0)

  1. 暂无评论