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.
+4
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); }); +8
.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