views:

61

answers:

2

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.

+9  A: 

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);
Nick Craver
+1 for pointing out non-jquery method; it's overkill for a simple thing like this. IMHO, people depend on it way too often.
amphetamachine
+1  A: 
$('#my-wrapper')[0].tagName
redsquare
`nodeName` is better way to do it.
Sarfraz
nice care to explain why it is better and where tagName fails...
redsquare
@redsquare: sure: http://aleembawany.com/2009/02/11/tagname-vs-nodename/
Sarfraz
showing my age then I guess, not much benefit and tagName saves k ;)
redsquare
Some additional reference (bottom/notes): https://developer.mozilla.org/en/DOM/element.nodeName
Nick Craver
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`.
bobince
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.
Tim Down