jquery selectors (finding tag)
I'开发者_如何学Cm 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"?
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;
You can use the DOM property tagName
like this:
document.getElementById('first').tagName
Or with jQuery, you would need to do:
$('#first')[0].tagName
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
$("#first").attr("tagName");
精彩评论