8

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.

eozzy
  • 66,048
  • 104
  • 272
  • 428

3 Answers3

17

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 )
David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

there are two ways:

1. check the length:

if ( !$(".first.last").length ) { // check the length if none returns 0 == false

2. check the visibility:

if ( !$(".first.last").is(':visible') ) { // returns boolean true/false
Jai
  • 74,255
  • 12
  • 74
  • 103
0

You can simplify this by checking the first object that is returned from JQuery:

if (!$(".first.last")[0]){
    console.log("div with both first and last classes does not exists");
} else {
  console.log("it exists");
}
Susheel Singh
  • 3,824
  • 5
  • 31
  • 66