Muhammad Usman
Muhammad Usman

Reputation: 10926

How to get the child div in jquery

I want to get the child div of main div

<div class="test">
<div id="dog"></div>
<div id="cat"></div>
<div id="drig"></div>
</div>

var a= $("div.test #dog");

alert (a);


var b= $("div.test #abc");

alert (b);

The problem is both a and b are returning the [object object]. where as there is no child id abc

JS Fiddle http://jsfiddle.net/8yJNS/

Upvotes: 1

Views: 174

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Returning [Object object] is expected from your code as even if no element is found, jQuery will return an empty jQuery object.

If you want to check whether the selector found anything, use length:

var a = $("div.test #dog");
alert(a.length); // 1 element found

var b = $("div.test #abc");
alert(b.length); // 0 elements found

Example fiddle

Upvotes: 3

Pranay Rana
Pranay Rana

Reputation: 176886

You can get id by something as below...

var a= $("div.test #dog"); 
 alert (a.id); 

or

   $(a).attr('id');

Upvotes: 2

Related Questions