Cosmin Cosmin - 2 months ago 10
jQuery Question

Use jQuery to target a class within a div and perform additional changes within the same div

I have the following HTML code:

<div class="pack1">
<a class="optionButton">First option</a>
<a class="optionButton">Second option</a>
<a class="optionButton">Third option</a>
</div>

<div class="pack2">
<a class="optionButton">First option</a>
<a class="optionButton">Second option</a>
<a class="optionButton">Third option</a>
</div>

<div class="pack3">
<a class="optionButton">First option</a>
<a class="optionButton">Second option</a>
<a class="optionButton">Third option</a>
</div>

[...]

<div class="pack10">
<a class="optionButton">First option</a>
<a class="optionButton">Second option</a>
<a class="optionButton">Third option</a>
</div>


Using jQuery I would like to trigger an event on clicking the
a
tag with the
optionButton
class but I don't know how to limit the event to the div that the
a
tag resides in.

For example right now I have something like:

$(document).ready(function(){
$('.optionButton').click(function() {
$(".optionButton").removeClass('checked');
$(this).addClass('checked');
});
});


It works fine for the first selection, lets say when I click the
First option
in the
pack1
div, but if I make another selection, lets say
Third option
in the
pack3
div, the first one will disapear.

Also, there must be only one selected option for each pach.

Answer

Because exact DOM structure is highly subject to change, your best bet is to almost always go to the parent and search your way down like so:

1) $(this).parent().find(".optionButton").removeClass("checked");

or you can simplify the selector results set (and make your code slightly more efficient) by saying:

2) $(this).parent().find(".checked").removeClass("checked");

You can also use the selector context parameter like so:

3) $(".checked", $(this).parent()).removeClass("checked");

The difference between 2 and 3 is purely syntactic. jQuery will convert 3 into 2 behind the scenes