3

I know you can do this, but every time I Google it I get how to select all elements of a certain tag.

So, e.g.:

alert($('#my-wrapper').someJSMethod());
{...}
<div id="my-wrapper"></div>

Would alert "DIV" actually. I'm selecting elements with jQuery by the way.

2 Answers 2

9

You can do this:

alert($('#my-wrapper').get(0).nodeName);
//or:
alert($('#my-wrapper')[0].nodeName);

Or, no need for jQuery:

alert(document.getElementById('my-wrapper').nodeName);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for pointing out non-jquery method; it's overkill for a simple thing like this. IMHO, people depend on it way too often.
1
$('#my-wrapper')[0].tagName

5 Comments

nodeName is better way to do it.
showing my age then I guess, not much benefit and tagName saves k ;)
Some additional reference (bottom/notes): developer.mozilla.org/en/DOM/element.nodeName
For me tagName is preferable, if it's definitely a tag name you want. It's marginally more readable and if you make a mistake it's slightly more obvious in that you get undefined instead of a fairly-arbitrary string for other nodeTypes. (It's not as obvious as it should be, though, since undefined is a horrible wrongness. A reasonable language would have raised an exception.) I completely disagree with the linked site that #text is somehow preferable to undefined, and feel that on IE, nodeName's failure case on Document is worse than tagName's unexpected existence on Comment.
If you're definitely dealing with an element (which we are in this case) then it makes no functional difference at all whether you use nodeName or tagName. Beyond that, it's a matter of personal taste. I tend to use nodeName, for no particular reason.

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.