title

Get the child tag of the item

I want to get the child name of the element tag.

HTML:

<div class="element"> <h1>title</h1> </div> <div class="element"> <img src="http://2.bp.blogspot.com/-ma66w8WJsZ0/UBVcmt3XS4I/AAAAAAAAAWw/4UyVd2eR8A0/s1600/olympic-logo.thumbnail.jpg" /> </div> <div id="debugger"></div> 

JQuery:

 $(".element").bind("click", function(){ var child = $(this).add("first-child").prop("tagName"); $("#debugger").html(child); });​ 

I do not understand why I always get a DIV as a result ...

Thanks.

http://jsfiddle.net/8Xg3G/2/

+4
source share
4 answers
 $(this).children()[0].tagName 

OR

 $(this).children().first().prop('tagName'); 

.add() used to add a new element to the jQuery object array, but you are trying to get the existing element tag name. So you need getter method.


With javascript

 this.firstChild.tagName 

OR

 this.childNodes[0].tagName 

Full code

 $(".element").bind("click", function(){ var child = $(this).children().first().prop('tagName'); $("#debugger").html(child); }); 

Demo

+8
source

.add will add the item to the current jQuery collection, in this case $(this) . $(this) contains a div , and when you run .prop('tagName') jQuery returns the tag name of the first element in the collection, so you get the result of "div".

Try .children instead:

 var child = $(this).children().eq(0).prop("tagName"); 
+4
source

Try:

 var child = $(this).children(":first"); 

This will get the first child of this .

Pretty sure .prop('tagName') only works in jQuery .prop('tagName') .

+2
source

You can use the target property of the event object, try the following:

 $(".element").bind("click", function(event){ var target = event.target.localName; // or event.target.tagName; $("#debugger").html(target); }); 

Fiddle

+1
source

All Articles