how to judge an element's previous or next element exist with jquery?

前端 未结 4 1285
说谎
说谎 2020-12-10 02:14

suppose I have an

    :

相关标签:
4条回答
  • 2020-12-10 02:35
    if ($("li.test").next().length > 0) { ... }
    

    http://jsfiddle.net/Kfsku/

    0 讨论(0)
  • 2020-12-10 02:36

    You need to check the length property.

    if ($("li.test").next().length) {
      //has next 
    } else {
      //last elem
    }
    

    Keep in mind that jQuery usually returns itself so you can chain. Getting the length property of that object will give you the information

    0 讨论(0)
  • 2020-12-10 02:45

    $("li.test").next().length;

    Example

    0 讨论(0)
  • 2020-12-10 02:49

    A jQuery selection will always evaluate to boolean true (as in an if statement). This is because it is not a native Javascript type -- it is an object.

    You need to check the length property of the selection. If it is empty, this will be 0 and will evaluate to false, so the if will not pass. If it is not empty, it will be a positive integer and will therefore evaluate to true, so the conditional will pass.

    if ($("li.test").next().length) { …… }
    
    0 讨论(0)
提交回复
热议问题