Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

suppose I have an <ul> :

<ul>
    <li></li>
    <li></li>
    <li class="test"></li>
</ul>

How can I judge the .test have its next element with jquery ? like this?:

if ($("li.test").next()) { …… }

the strange thing is that ,even I write like above:

if ($("li.test").next()) {alert("true");}

it still alert "true",but as you see,there is no element next to it ?why this happened?

Or what I can do is

        for (i = 0; i < $("li").length; i++) {
            if ($("li").eq(i).hasClass("test")) {
                if (i == $("li").length - 1) {
                    alert("true");
                }
            }
        }

presently this could solve my problem,but is there a easy way?

thank you

like image 695
hh54188 Avatar asked Apr 16 '11 09:04

hh54188


People also ask

How can I get next sibling in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

How do you find if element with specific ID exists or not?

Approach 1: First, we will use document. getElementById() to get the ID and store the ID into a variable. Then compare the element (variable that store ID) with 'null' and identify whether the element exists or not.


2 Answers

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) { …… }
like image 114
lonesomeday Avatar answered Oct 11 '22 12:10

lonesomeday


if ($("li.test").next().length > 0) { ... }

http://jsfiddle.net/Kfsku/

like image 25
Alex Wayne Avatar answered Oct 11 '22 10:10

Alex Wayne