5

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.

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

2 Comments

took the words right out of my mouth, well, clicks out of my keyboard, actually...
Results can vary on text nodes and attribute nodes, but HTML elements should give the exact same result when using tagName and nodeName. So if you know that your node is an HTML element, it shouldn't really matter. Right?!
1

tagName or nodeName

Comments

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

Comments

0

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>

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.