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'
.
$("div").
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.
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.
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.
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"
You can use the DOM's nodeName
property:
$(...)[0].nodeName
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With