tags:

views:

64

answers:

4

I'm sure this is simple, but I can't seem to figure it out. I need to be able to pass a function an element id, and know what element tag it is.

For example:

<a id="first"></a>
<input id="last" />

If I know the id is "first", how can I get that the tag is "a"?

+4  A: 

This should do it:

var tagName = $("#first")[0].tagName;

The [0] is synonymous with get(0). You get the first element from the jQuery object and use the DOM tagName property. It's arguably more straightforward in vanilla Javascript:

var tagName = document.getElementById("first").tagName;
cletus
+2  A: 

You can use the DOM property tagName like this:

document.getElementById('first').tagName

Or with jQuery, you would need to do:

$('#first')[0].tagName
wsanville
+1  A: 

$("#first").attr("tagName");

F.Aquino
I don't think this will work. `tagName` is not an attribute.
Jacob Relkin
@Jacob - Don't knock it :) http://jsfiddle.net/J8eUS/ But...I agree it's an over-use of jQuery in this case.
Nick Craver
@Nick, that is unbelievable!
Jacob Relkin
@Nick I still think is cleaner code. Readability vs Performance I guess? I usually do everything jqueryish when working with it, creates a code pattern of clean, concise code.
F.Aquino
+2  A: 

I would use .nodeName here (there are a few reasons this matters), like this:

$("#first").get(0).nodeName
//or the vanilla js way...
document.getElementById("first").nodeName
Nick Craver
None of those differences are relevant here.
cletus
@cletus - True, but seeing as the OP doesn't know `.tagName` or `.nodeName` yet, I think it's best to point out the differences when first learning either.
Nick Craver