Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery tag name of element

Tags:

html

jquery

tags

I'm try to get an elements tag name in jQuery.

I have the following html:

<div class="section" id="New_Revision">

    <h1>New Revision&nbsp<img alt="Lock_closed" class="edit" data-id="1" src="/assets/lock_closed.svg" /></h1>

    <p>This is a test paragraph.</p>

    <ol class="references">
      <li>test</li>
    </ol>
</div>

And javascript:

$(".edit").click(function(){
    $(this).closest("div.section").children().each(function(){
        alert($(this).tagName + " - " + $(this).html());
    });     
})

I've tried $(this).tagName, $(this).nodeName and $(this).attr("tag") as noted in this question: Can jQuery provide the tag name?

But I'm always getting undefined in return. The html() outputs correctly. Why can't I get the tag name of each element?

like image 808
Ryan King Avatar asked Apr 13 '13 14:04

Ryan King


People also ask

What is $() in jQuery?

In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.

What's the equivalent of Getelementsbytagname in jQuery?

$("div").

What is jQuery selector?

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors. All selectors in jQuery start with the dollar sign and parentheses: $().

What does jQuery selector return?

The jQuery Object: The Wrapped Set: Selectors return a jQuery object known as the "wrapped set," which is an array-like structure that contains all the selected DOM elements. You can iterate over the wrapped set like an array or access individual elements via the indexer ($(sel)[0] for example).


2 Answers

Try

this.nodeName instead of $(this).nodeName

this refers to the DOM element itself and $(this) wraps the element up in a jQuery object.

EDIT

If you require Jquery approach you can use

$(this).prop("tagName")
like image 59
ssilas777 Avatar answered Oct 12 '22 05:10

ssilas777


Have you tried:

$(this).attr("id", "rnd" + this.nodeName.toLowerCase() + "_" + i.toString());

As stated in the linked question. Also there is a big difference between $(this) and this

Tried this in the browser console and it works:

document.getElementsByTagName("a")[0].tagName // this uses javascript

this uses jquery:

$('a').get(0).nodeName; // this works for jquery

try this:

$(".edit").click(function(){
    $(this).closest("div.section").children().each(function(){
        alert(this.tagName + " - " + $(this).html());
    });     
})
like image 5
radu florescu Avatar answered Oct 12 '22 05:10

radu florescu