Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Get selected element tag name

Is there an easy way to get a tag name?

For example, if I am given $('a') into a function, I want to get 'a'.

like image 582
configurator Avatar asked Mar 18 '11 02:03

configurator


People also ask

What's the equivalent of Getelementsbytagname in jQuery?

$("div").

How do I get DOM element?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

What does jQuery find return?

jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.

How do you target a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.


2 Answers

You can call .prop("tagName"). Examples:

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


If writing out .prop("tagName") is tedious, you can create a custom function like so:

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

Examples:

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


Note that tag names are, by convention, returned CAPITALIZED. If you want the returned tag name to be all lowercase, you can edit the custom function like so:

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

Examples:

jQuery("<a>").tagNameLowerCase(); //==> "a" jQuery("<h1>").tagNameLowerCase(); //==> "h1" jQuery("<coolTagName999>").tagNameLowerCase(); //==> "cooltagname999" 
like image 128
tilleryj Avatar answered Oct 21 '22 16:10

tilleryj


You can use the DOM's nodeName property:

$(...)[0].nodeName 
like image 27
SLaks Avatar answered Oct 21 '22 15:10

SLaks