How to check jQuery find return true or false?

This question already has an answer here:

  • Check if element exists in jQuery [duplicate] 8 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
    }
    

    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')
    }
    

    Whenever you wrap a selector in $() it will always return a jQuery object that contains the array of matching elements.

    Therefore you can use the length property to test if there are matches

    var $collection = $(".parent2").find(".child3").length;
    if ($collection.length)....
    

    You can use other approaches also such as is()

    var #collection = $(".parent2");
    if($collection.children().is(".child3") /* returns tru if there are matches
    
    链接地址: http://www.djcxy.com/p/83686.html

    上一篇: 没有条件失败(jQuery)

    下一篇: 如何检查jQuery查找返回true或false?