Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child tagname of an element

Tags:

jquery

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/

like image 717
vpascoal Avatar asked Aug 16 '12 12:08

vpascoal


2 Answers

$(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

like image 167
thecodeparadox Avatar answered Oct 20 '22 22:10

thecodeparadox


.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");
like image 30
jackwanders Avatar answered Oct 20 '22 22:10

jackwanders