I want to get the child tag name of an element.
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 don't understand why I'm always getting DIV as the result...
Thank you.
http://jsfiddle.net/8Xg3G/2/
$(this).children()[0].tagName
OR
$(this).children().first().prop('tagName');
.add()
used for add new element to jQuery object array, but you're trying to get an existing element's tag name. So, you need some 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
.add
will add an element to the current jQuery collection, in this case, $(this)
. $(this)
contains the div
, and when you run .prop('tagName')
, jQuery returns the tag name of the first element in the collection, so you get "div" as a result.
Try .children
instead:
var child = $(this).children().eq(0).prop("tagName");
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