Search code examples
jqueryjquery-selectors

jQuery - using next()


In the following situation, I would like to add a class "highlight" to the succeeding div.second when div.first > a is clicked.

html:

<li>
    <div class="first">
        <a href="#">link</a>
    </div>
    <div class="second">
        text to be highlighted
    </div>
</li>
<!--(repeats)-->

js:

$("div.first > a").click(function() {
    $(this).next("div.second").addClass("highlight");   
});

I know its wrong, but I don't know how to do it correctly. Help please.


Solution

  • .next() finds the next sibling of the current element. Your current element is <a>, which, in this case, has no siblings (the poor thing). Use parent() to retrieve the containing <div>, and then use next() to find <div> that is to be highlighted.

    $("div.first > a").click(function() {
        $(this).parent().next("div.second").addClass("highlight");   
    });