jQuery: Checking if next element exists
Use the length
method in jQuery:
if($(...).next().length > 0) {
alert("Exists.")
} else {
alert("Doesn't exist!")
}
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.
Have you tried looking at .next('li').length
?
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");
}