0

for example I have a div <div id="myrules"></div>

If i use

alert($("#myrules").find("if"))

it alerts [object object] , even though the div is empty, so the question is how to tell if the child exists or not using .find()?

http://jsfiddle.net/prollygeek/agG3d/

Popnoodles
  • 28,090
  • 2
  • 45
  • 53
ProllyGeek
  • 15,517
  • 9
  • 53
  • 72
  • are you looking for child elements or any children including non empty text nodes – Arun P Johny Dec 07 '13 at 04:45
  • 2
    There are countless duplicates; one possible duplicate is [Is there an "exists" function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery). – Kevin Ji Dec 07 '13 at 04:47
  • FWIW, using `console` functions is superior to alert since they are able to print out things like objects and multiple arguments much clearer. If you used `console.log($('blah')) you would see that what was returned would be an empty "array-like" object since that is what jQuery does is [create a collection of DOM objects](http://api.jquery.com/Types/#jQuery). – gillyspy Dec 07 '13 at 05:10

5 Answers5

4

You can use $('#myrules').find('if').length

Rob
  • 12,659
  • 4
  • 39
  • 56
2

jQuery returns a set of matched elements, this set is empty if no elements were selected, so you need to check against the length property of the returned value.

// "length" of the returned collection is 0
if(jQuery('#myelem').find('.idontexist').length)
  alert("element found");

Also to be found here: http://api.jquery.com/jQuery/

LJᛃ
  • 7,655
  • 2
  • 24
  • 35
2

You can check children of an element like:

HTML

<div id="myrules">
    <div class="ch">1</div>
    <div class="ch">2</div>
    <p>3</p>
</div>

jQuery:

alert($("#myrules").children().length) // Alerts total children exists

Also you can check specific total children in an element:

alert($("#myrules").children('div').length)
alert($("#myrules").children('p').length)

http://jsfiddle.net/agG3d/1/

sravis
  • 3,562
  • 6
  • 36
  • 73
1

Try this:

alert($($("#myrules").find("#am")).length);
Musfiqur rahman
  • 749
  • 4
  • 12
1

Try this

if($('#myrules').children('div').length > 0){}
Mr.G
  • 3,413
  • 2
  • 16
  • 20