In jQuery, when working with selected elements, it’s often necessary to determine the tag name of those elements. The tag name is essentially the type of HTML element, such as div
, span
, a
, etc., and understanding how to retrieve this information can be crucial for various applications, including dynamic content manipulation, event handling, and more.
To get the tag name of a selected element in jQuery, you can use several approaches. One of the most straightforward methods involves utilizing the .prop()
function provided by jQuery. The .prop()
method gets or sets the value of a property for the first element in the set of matched elements or sets one or more properties for every matched element.
Here’s how you can use it to get the tag name:
// Example usage:
var tagName = $('a').prop("tagName");
console.log(tagName); // Output: "A"
As shown, $('a').prop("tagName")
will return "A"
, which is the tag name of the selected <a>
elements. Note that tag names are returned in uppercase by convention.
If you prefer a more concise way to achieve this or need to perform this operation frequently, you can extend jQuery with a custom function:
// Extending jQuery with a custom tagName function
jQuery.fn.tagName = function() {
return this.prop("tagName");
};
// Example usage:
var tagName = $('h1').tagName();
console.log(tagName); // Output: "H1"
This approach simplifies the process by encapsulating the .prop("tagName")
call within a tagName()
method that you can use directly on jQuery objects.
For cases where you want the tag name in lowercase (e.g., "a"
instead of "A"
), you can modify the custom function to include a call to .toLowerCase()
:
// Custom function for getting the tag name in lowercase
jQuery.fn.tagNameLowerCase = function() {
return this.prop("tagName").toLowerCase();
};
// Example usage:
var tagNameLower = $('a').tagNameLowerCase();
console.log(tagNameLower); // Output: "a"
Alternatively, without extending jQuery, you can achieve the same result by accessing the DOM node directly and using its nodeName
property or tagName
property:
// Using nodeName or tagName on a DOM node
var element = $('a')[0];
console.log(element.nodeName); // Output: "A"
console.log(element.tagName); // Output: "A"
Or, more concisely with jQuery’s .prop()
method for compatibility across different versions of jQuery:
// Using prop() for tagName, compatible with jQuery 1.6+
var tagName = $('a').prop("tagName");
console.log(tagName); // Output: "A"
In summary, getting the tag name of a selected element in jQuery can be accomplished through several methods, including using .prop("tagName")
, creating custom functions for convenience, or accessing DOM node properties directly. The choice between these approaches depends on your specific requirements and preferences.