user6890
user6890

Reputation: 484

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")

Upvotes: 8

Views: 11488

Answers (1)

James Allardice
James Allardice

Reputation: 166031

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);
});

Upvotes: 19

Related Questions