Find siblings for the clicked element
jquery, siblings
Solution
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
});
Problem
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 } ```