user2271933
user2271933

Reputation: 491

Find siblings for the clicked element

I have the following list structure:

<ul>
    <a class="target">one</a>
    <a class="target">two</a>
    <a class="target">three</a>
</ul>

When i click an <a> element I add an "selected" class for the clicked element and a "unselected" class for the others a elements like this:

$(".target").click(){
    $(this).siblings().removeClass("selectedClass"); //remove "selected" class from siblings
    $(this).addClass("selectedClass"); //add selected class to clicked element
}

Now comes my problem.If I change the list structure as follows(wrap the <a> into divs):

    <ul>
    <div><a class="target">one</a></div
    <div><a class="target">two</a></div
    <div><a class="target">three</a></div
    </ul>

I don't know how to find the siblings (the others <a> elements) for the one I clicked.

    $(".target").click(){
        // how to target the others two <a> elements to call removeClass on them?    
        $(this).addClass("selectedClass"); //add selected class to clicked element - still works
    }

Upvotes: 3

Views: 6516

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You just confused up with the syntaxes in binding a click event,

$(".target").click(function(){
    $(this).siblings().removeClass("selectedClass"); //remove "selected" class from siblings
    $(this).addClass("selectedClass"); //add selected class to clicked element
});

You supposed to write the click event's code inside an anonymous function. or simply write the code in a separate function and just pass the reference to it.

I just saw your html structure, its invalid. Anchor tag should not be the direct child of an unordered list.

DEMO

Modified HTML:

<ul>
    <li><a class="target">one</a></li>
    <li><a class="target">two</a></li>
    <li><a class="target">three</a></li>
</ul>

Modified JS:

$(".target").click(function () {
    var parent = $(this).parent()
    parent.siblings().removeClass("selectedClass"); //remove "selected" class from siblings
    parent.addClass("selectedClass"); //add selected class to clicked element
});

Upvotes: 4

Ja͢ck
Ja͢ck

Reputation: 173562

Actually, you can design it in such a way whereby it's not necessary to know exactly where the other items are; for instance, by keeping the last selected element and changing only that and the one currently clicked:

jQuery(function($) {
    var $current = $();

    $(".target").click(function() {
        $current.removeClass('selectedClass');
        $current = $(this).addClass('selectedClass');
    });
});

Alternatively, just cache all the target elements in one go:

jQuery(function($) {
    var $targets = $('.target');

    $targets.on('click', function() {
        $targets.removeClass('selectedClass');
        $(this).addClass('selectedClass');
    });
});

Upvotes: 1

Related Questions