2

I want to test if an element with a specific class name exists or not.
Here's my code:

<div class="album-tracks">
    <div class="track">
        <div class="play-status">
            <span class="add-to-list">
                <i class="fa fa-play" aria-hidden="true"></i>
            </span>
        </div
        ><div class="track-num">1</div
        ><div class="track-name">A Head Full Of Dreams</div
        ><div class="track-time">03:44</div
        ><div class="track-artist">Coldplay</div>
            <!-- <div class="track-album"></div> -->
    </div>
</div>

JS

$('.track').dblclick(function() {
    var $prev;
    $prev = $(this).parent('div').find('.status-active');
    if ($prev != null) {
        //This will always be true
    }
}

And the picture below is the screenshot of the console console

I'm confused by the layers of the object. It means that even if I did't get the object with the class that I want, I still get the object with the parent element. So the object is not null, and the result will always be true?

I have found the solution to fix the mistake is that I need to use the lengthproperty.

if($prev.length){
    //This works!
}

Just want to clarify the idea that when can I test the result using null value? I'll be appreciate if you give me some advice!!

CodeMonkey
  • 2,828
  • 1
  • 23
  • 32
hayley
  • 384
  • 5
  • 17
  • 1
    `jQuery()` does not return `null` – guest271314 Apr 24 '17 at 03:36
  • 3
    The `$()` function, and other DOM navigation methods like `.parent()`, `.find()`, etc., will always return a jQuery object, containing zero, one, or many elements depending on how many matched the selector. **It will never return `null`.** That's why you would use `length` to see how many matched. – nnnnnn Apr 24 '17 at 03:36
  • See [Is there an “exists” function for jQuery?](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery) – guest271314 Apr 24 '17 at 03:38
  • This question has been answered in [Check if an element is a child of a parent](http://stackoverflow.com/questions/3753634/check-if-an-element-is-a-child-of-a-parent) and [jQuery - How to determine if a parent element exists?](http://stackoverflow.com/questions/2691873/jquery-how-to-determine-if-a-parent-element-exists). It seems `element.length >0` will work for you. – CodeMonkey Apr 24 '17 at 03:38
  • 1
    You can also use `.is()` `if ($prev.is("*"))` – guest271314 Apr 24 '17 at 03:39

0 Answers0