javascript tutorial - [Solved-5 Solutions] jQuery : get selected element tag name - javascript - java script - javascript array
Problem:
Is there an easy way to get a tag name?
For example, if we are given $('a')
into a function, We want to get 'a'
.
Solution 1:
We can call .prop("tagName"). Examples:
jQuery("<a>").prop("tagName"); //==> "A"
jQuery("<h1>").prop("tagName"); //==> "H1"
jQuery("<coolTagName999>").prop("tagName"); //==> "COOLTAGNAME999"
click below button to copy the code. By JavaScript tutorial team
If writing out .prop("tagName") is tedious, we can create a custom function like so:
jQuery.fn.tagName = function() {
return this.prop("tagName");
};
click below button to copy the code. By JavaScript tutorial team
Examples:
jQuery("<a>").tagName(); //==> "A"
jQuery("<h1>").tagName(); //==> "H1"
jQuery("<coolTagName999>").tagName(); //==> "COOLTAGNAME999"
click below button to copy the code. By JavaScript tutorial team
Note that tag names are, by convention, returned CAPITALIZED. If we want the returned tag name to be all lowercase, we can edit the custom function like so:
jQuery.fn.tagNameLowerCase = function() {
return this.prop("tagName").toLowerCase();
};
click below button to copy the code. By JavaScript tutorial team
Examples:
jQuery("<a>").tagNameLowerCase(); //==> "a"
jQuery("<h1>").tagNameLowerCase(); //==> "h1"
jQuery("<coolTagName999>").tagNameLowerCase(); //==> "cooltagname999"
click below button to copy the code. By JavaScript tutorial team
Solution 2:
We can use the DOM's nodeName property
$(...)[0].nodeName
click below button to copy the code. By JavaScript tutorial team
Solution 3:
As of jQuery 1.6 we should now call prop:
$target.prop("tagName")
click below button to copy the code. By JavaScript tutorial team
Solution 4:
jQuery 1.6+
jQuery('selector').prop("tagName").toLowerCase()
click below button to copy the code. By JavaScript tutorial team
Older versions
jQuery('selector').attr("tagName").toLowerCase()
click below button to copy the code. By JavaScript tutorial team
toLowerCase() is not mandatory.
Solution 5:
This is yet another way:
$('selector')[0].tagName