Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if-not condition fails (jQuery) [duplicate]

http://jsbin.com/zexix/1/

$(function() {

    if ( !$(".first.last") ) {
      console.log("div with both first and last classes does not exists")
    } else {
      console.log("it exists");
    }

});

I want to check if a div with both first and last classes DOES NOT exist, but the check fails.

like image 986
eozzy Avatar asked May 12 '14 22:05

eozzy


Video Answer


1 Answers

You need to check the number of elements found, as jQuery returns an empty collection in the event of no elements being found (which evaluates to a truthy value in the if statement):

if ( !$(".first.last").length )

I'd suggest testing against 0 explicitly, rather than relying on a falsey value, though:

if ( $(".first.last").length === 0 )
like image 175
David Thomas Avatar answered Oct 02 '22 03:10

David Thomas