5

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/

vpascoal
  • 278
  • 2
  • 4
  • 15
  • possible duplicate of [Can jQuery provide the tag name?](http://stackoverflow.com/questions/1532331/can-jquery-provide-the-tag-name) – Mild Fuzz Aug 16 '12 at 12:54

4 Answers4

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

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
4

.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");
jackwanders
  • 15,612
  • 3
  • 40
  • 40
3

Try:

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

This will get the first child of this.

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

Flash
  • 15,945
  • 13
  • 70
  • 98
1

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

Ram
  • 143,282
  • 16
  • 168
  • 197