Lucas Veiga
Lucas Veiga

Reputation: 1795

jQuery: Checking if next element exists

Is there a way to check if a next element exists? Check my code:

if($("#people .making-of .mask ul li.current").next("li") != null) {
    alert("Exists");
}
else {
    alert("Dont exists");
}

What am I doing wrong? Thanks a lot!

Upvotes: 61

Views: 103545

Answers (7)

Yogendra Tomar
Yogendra Tomar

Reputation: 121

I think this is good to use like.

   if ($(this).nextAll().length > 0) { 

     alert("Exists");

   }else{

     alert("Don't exists");

   }

Upvotes: 0

Wallace Vizerra
Wallace Vizerra

Reputation: 3542

Use the length method in jQuery:

if($(...).next().length > 0) {
    alert("Exists.")
} else {
    alert("Doesn't exist!")
}

Upvotes: 5

Mohsen
Mohsen

Reputation: 65785

Use jQuery .is(), using .is() you can even check what tag, class or ID next element have?

if($("#people .making-of .mask ul li.current").next().is('li')) {
    alert("Exists");
}
else {
    alert("Dont exists");
}

Upvotes: 26

DSKrepps
DSKrepps

Reputation: 641

The briefest method is just:

if( $( ... ).next('li')[0] ) {

Since jQuery functions always return a jQuery object, it's never equal to null. But accessing a jQuery object like an array acts like you are using an array of DOM objects, so [0] will pull the first matched DOM element or null. Checking .length() against 0 works, as well.

Upvotes: 14

George
George

Reputation: 1556

Have you tried looking at .next('li').length?

Upvotes: 152

mattgmg1990
mattgmg1990

Reputation: 5876

Like the post above says, you need to check the length of the item. Jquery.next() will always return a jquery object, but if there is no next item, it will have a length of 0.

if($("#people .making-of .mask ul li.current").next("li").length > 0) {
    alert("Exists");
}
else {
    alert("Dont exists");
}

Upvotes: 1

HashTagDevDude
HashTagDevDude

Reputation: 574

if($("#people .making-of .mask ul li.current").next("li").length > 0) {
    alert("Exists");
}
else {
    alert("Dont exists");
}

Upvotes: 3

Related Questions