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

How to Easily Get the Tag Name of a Selected jQuery Element?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-27 20:38:10872browse

How to Easily Get the Tag Name of a Selected jQuery Element?

How to Retrieve the Tag Name of a Selected Element in jQuery

In jQuery, we often manipulate elements on a web page. Sometimes, it's useful to retrieve the tag name of the element we're working with.

Is there an easy way to get a tag name?

For instance, say you're given $('a') in a function and want to obtain the 'a' tag name.

Answer

To retrieve the tag name, you can use the .prop("tagName") method. Here are some examples:

jQuery("<a>").prop("tagName"); //==> "A"
jQuery("<h1>").prop("tagName"); //==> "H1"
jQuery("<coolTagName999>").prop("tagName"); //==> "COOLTAGNAME999"

If writing out .prop("tagName") is cumbersome, you can define a custom function:

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

Examples:

jQuery("<a>").tagName(); //==> "A"
jQuery("<h1>").tagName(); //==> "H1"
jQuery("<coolTagName999>").tagName(); //==> "COOLTAGNAME999"

By convention, tag names are returned capitalized. If you prefer lowercase tag names, modify the custom function:

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

Examples:

jQuery("<a>").tagNameLowerCase(); //==> "a"
jQuery("<h1>").tagNameLowerCase(); //==> "h1"
jQuery("<coolTagName999>").tagNameLowerCase(); //==> "cooltagname999"

The above is the detailed content of How to Easily Get the Tag Name of a Selected jQuery Element?. 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