Home > Web Front-end > CSS Tutorial > How Can I Easily Get the Tag Name of a Selected Element Using jQuery?

How Can I Easily Get the Tag Name of a Selected Element Using jQuery?

Barbara Streisand
Release: 2024-11-28 14:37:10
Original
430 people have browsed it

How Can I Easily Get the Tag Name of a Selected Element Using jQuery?

Retrieving the Tag Name of a Selected Element with jQuery

Seeking an effortless approach to obtaining the tag name of a given element within a jQuery selector? This guide provides comprehensive guidance on employing the .prop("tagName") method to swiftly capture tag names.

Solution via .prop("tagName"):

To determine the tag name of a given jQuery object $('selector'), simply utilize the .prop("tagName") function. For instance:

jQuery("a").prop("tagName"); // Outputs "A"
jQuery("h1").prop("tagName"); // Outputs "H1"
jQuery("<coolTagName999>").prop("tagName"); // Outputs "COOLTAGNAME999"
Copy after login

Custom Function for Simplification:

To streamline the process, a custom function can be defined:

jQuery.fn.tagName = function() {
  return this.prop("tagName");
};
Copy after login

This simplifies the syntax, allowing for easy retrieval of tag names:

jQuery("a").tagName(); // Outputs "A"
jQuery("h1").tagName(); // Outputs "H1"
jQuery("<coolTagName999>").tagName(); // Outputs "COOLTAGNAME999"
Copy after login

Lowercase Tag Name Support:

By convention, tag names are returned in uppercase. To retrieve lowercase tag names, modify the custom function:

jQuery.fn.tagNameLowerCase = function() {
  return this.prop("tagName").toLowerCase();
};
Copy after login

This function will output lowercase tag names:

jQuery("a").tagNameLowerCase(); // Outputs "a"
jQuery("h1").tagNameLowerCase(); // Outputs "h1"
jQuery("<coolTagName999>").tagNameLowerCase(); // Outputs "cooltagname999"
Copy after login

The above is the detailed content of How Can I Easily Get the Tag Name of a Selected Element Using jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template