Knowing the tag name of a selected element can be beneficial in various scenarios. jQuery provides a convenient way to access this information.
Using .prop("tagName")
To retrieve the tag name of a selected element, you can utilize the ".prop('tagName')" method. This method provides the element's tag name as a string. For instance:
jQuery("<a>").prop("tagName"); // Returns "A" jQuery("<h1>").prop("tagName"); // Returns "H1" jQuery("<coolTagName999>").prop("tagName"); // Returns "COOLTAGNAME999"
Tag names are conventionally capitalized in the returned value.
Creating a Custom Function
If you find writing ".prop('tagName')" cumbersome, you can create a custom function:
jQuery.fn.tagName = function() { return this.prop("tagName"); };
This function can be used as follows:
jQuery("<a>").tagName(); // Returns "A" jQuery("<h1>").tagName(); // Returns "H1" jQuery("<coolTagName999>").tagName(); // Returns "COOLTAGNAME999"
Getting the Tag Name in Lowercase
To obtain the tag name in lowercase, edit the custom function as follows:
jQuery.fn.tagNameLowerCase = function() { return this.prop("tagName").toLowerCase(); };
This function can be used to retrieve the tag name in lowercase:
jQuery("<a>").tagNameLowerCase(); // Returns "a" jQuery("<h1>").tagNameLowerCase(); // Returns "h1" jQuery("<coolTagName999>").tagNameLowerCase(); // Returns "cooltagname999"
The above is the detailed content of How Can I Get a Selected Element\'s Tag Name Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!