16

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?

1

2 Answers 2

43

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") 
Sign up to request clarification or add additional context in comments.

5 Comments

this is using javascript not Jquery as stated in the question.
@Floradu That is what I also stated here.DOM means document object model.Why downvote?
as I stated before, he wanted a Jquery approach, not an Js approach, I removed the downvote
Thanks, this is simplest solution.
Well, if you really had wanted to use a jQuery function for some reason, you could have used $(this).prop('tagName') - but it's easier to just use this.tagName as ssilas777 said.
5

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

1 Comment

Thanks, but I having trouble seeing how to adapt this to the $(this).tagName code above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.