Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check jQuery find return true or false? [duplicate]

HTML Code

<div class="parent1">
    <div class="child1">Child1</div>
    <div class="child2">Child2</div>
    <div class="child3">Child3</div>
</div>

<div class="parent2">
    <div class="child1">Child1</div>
    <div class="child2">Child2</div>
</div>

jQuery Code

alert($(".parent1").find(".child3").text());
alert($(".parent2").find(".child3").text());

My question is how to check find function return true or false?

In above code it return blank value, where parent1 class have child3 class where parent2 class do not have child3 class.

JS Fiddle

like image 313
Sadikhasan Avatar asked Dec 25 '14 10:12

Sadikhasan


3 Answers

You couldn't use just find in if condition. You could use has or check for the length property.

var elm = $('.parent1');
if(elm.has('.child3')){
   var child3 = elm.find('.child3');
}

Or simply like this

var child3 = $('.parent1').find(".child3");
if(child3.length > 0) {
  // child3 is present
}
like image 171
Amit Joki Avatar answered Nov 08 '22 17:11

Amit Joki


You can use .length property to check that element exists.

var elem = $(".parent2").find(".child3");
if(elem.length){
    alert(elem.text());
}else{
    alert('Element doesnt exists')
}

Alternatively, You can use .has()

var elem = $(".parent2");
if(elem.has(".child3")){
    alert(elem.find(".child3").text());
}else{
    alert('Element doesnt exists')
}
like image 24
Satpal Avatar answered Nov 08 '22 15:11

Satpal


As the docs for find() explain, find() returns a jQuery object. It has a length propery which can be checked for a successful query.

if($(".parent1").find(".child3").length > 0) {
    alert("parent1 child3");
}
if($(".parent2").find(".child3").length > 0) {
    alert("parent2 child3");
}
like image 5
chrki Avatar answered Nov 08 '22 15:11

chrki