JQuery: checking for the next element

Is there a way to check if the following element exists? Check out my code:

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

What am I doing wrong? Thank you very much!

+45
javascript jquery
Oct 06 2018-11-17T00:
source share
6 answers

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

+112
06 Oct '11 at 18:01
source share

Use jQuery .is() , using .is() , can you even check which tags, classes or identifiers have the following element?

 if($("#people .making-of .mask ul li.current").next().is('li')) { alert("Exists"); } else { alert("Dont exists"); } 
+20
Oct 06 '11 at 18:07
source share

The shortest method:

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

Since jQuery functions always return a jQuery object, it is never null . But accessing a jQuery object like an array acts just like you use an array of DOM objects, so [0] will pull the first matched DOM element or null . It also checks .length() for 0.

+13
Oct 06 '11 at 18:07
source share
 if($("#people .making-of .mask ul li.current").next("li").length > 0) { alert("Exists"); } else { alert("Dont exists"); } 
+2
Oct 06 2018-11-18T00:
source share

As stated above, you need to check the length of the element. Jquery.next () will always return a jquery object, but if there is no next element, 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"); } 
+1
06 Oct '11 at 18:07
source share

Use the length method in jQuery:

 if($(...).next().length > 0) { alert("Exists.") } else { alert("Doesn't exist!") } 
+1
May 14 '15 at 15:43
source share



All Articles