jQuery: Checking if next element exists

后端 未结 7 779
庸人自扰
庸人自扰 2020-12-02 18:08

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         


        
相关标签:
7条回答
  • 2020-12-02 18:46

    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.

    0 讨论(0)
  • 2020-12-02 18:57

    Use the length method in jQuery:

    if($(...).next().length > 0) {
        alert("Exists.")
    } else {
        alert("Doesn't exist!")
    }
    
    0 讨论(0)
  • 2020-12-02 18:59

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

    0 讨论(0)
  • 2020-12-02 19:01

    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");
    }
    
    0 讨论(0)
  • 2020-12-02 19:02

    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");
    }
    
    0 讨论(0)
  • 2020-12-02 19:04
    if($("#people .making-of .mask ul li.current").next("li").length > 0) {
        alert("Exists");
    }
    else {
        alert("Dont exists");
    }
    
    0 讨论(0)
提交回复
热议问题