Home >Web Front-end >CSS Tutorial >How Can I Get a Selected Element\'s Tag Name Using jQuery?

How Can I Get a Selected Element\'s Tag Name Using jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 18:26:10376browse

How Can I Get a Selected Element's Tag Name Using jQuery?

Getting the Selected Element's Tag Name with jQuery

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!

Statement:
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