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
Release: 2024-11-27 20:38:10
Original
883 people have browsed it

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"
Copy after login

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

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

Examples:

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

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();
};
Copy after login

Examples:

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

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!

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