jQuery: Checking if next element exists

JavascriptJquery

Javascript Problem Overview


Is there a way to check if an 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!

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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");
}

Solution 3 - Javascript

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.

Solution 4 - Javascript

Use the length method in jQuery:

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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");
}

Solution 7 - Javascript

I think this is good to use like.

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

 alert("Exists");

}else{

 alert("Don't exists");

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLucas VeigaView Question on Stackoverflow
Solution 1 - JavascriptGeorgeView Answer on Stackoverflow
Solution 2 - JavascriptMohsenView Answer on Stackoverflow
Solution 3 - JavascriptDSKreppsView Answer on Stackoverflow
Solution 4 - JavascriptWallace MaxtersView Answer on Stackoverflow
Solution 5 - JavascriptHashTagDevDudeView Answer on Stackoverflow
Solution 6 - Javascriptmattgmg1990View Answer on Stackoverflow
Solution 7 - JavascriptYogendra TomarView Answer on Stackoverflow