Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selecting adjacent element

<li>
    <a class="handle" href="abc.htm">TopLink</a> 
    <ul class="container"> 
        <li> 
            <a href="xyz.htm">SubLink1</a> 
        </li>       
    </ul> 
</li>

When click on TopLink (class="handle");

Question: how to write jQuery selector in such a way to select ul class="container" whenever i click on TopLink

Something like; $(this).(Get the next UL with classname="container")

like image 244
user6890 Avatar asked Mar 21 '12 12:03

user6890


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.

What is prevObject in jQuery?

jQuery returns prevObject if the DOM does not have the element for which jQuery is being run. You might see the element in your source at the run-time however, it is not not bound to the DOM and therefore, it shows prevObject.

What is closest tr in jQuery?

jQuery closest() Method The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on.

What does siblings do in jQuery?

The siblings() is an inbuilt method in jQuery which is used to find all siblings elements of the selected element. The siblings are those having same parent element in DOM Tree. The DOM (Document Object Model) is a World Wide Web Consortium standard.


1 Answers

If that will always be the structure of your HTML, you can simply use next:

$(".handle").click(function() {
    var ul = $(this).next();
});

If there might be elements between the link and the ul, you could use siblings to get all elements that match the selector:

$(".handle").click(function() {
    var uls = $(this).siblings("ul.container");
});

Although that would also get preceding siblings. To just get following siblings, you could use nextAll:

$(".handle").click(function() {
    var uls = $(this).nextAll("ul.container");

    //You can then use `.eq(0)` to get the closest matching sibling:
    var sibling = uls.eq(0);
});
like image 143
James Allardice Avatar answered Nov 15 '22 16:11

James Allardice