How to control individual classes in jQuery?

1

I recently created this HTML document:

<div class="wrap">
<div class="container">
    <a class="button" href="#" title="Abrir as opções."></a>
    <div class="option-box">
        <ul>
            <li><a href="#">Ação 1</a></li>
            <li><a href="#">Ação 2</a></li>
            <li><a href="#">Ação 3</a></li>
            <li><a href="#">Ação 4</a></li>
        </ul>
    </div>
</div>
<div class="container">
    <a class="button" href="#" title="Abrir as opções."></a>
    <div class="option-box">
        <ul>
            <li><a href="#">Ação 1</a></li>
            <li><a href="#">Ação 2</a></li>
            <li><a href="#">Ação 3</a></li>
            <li><a href="#">Ação 4</a></li>
        </ul>
    </div>
</div>

I have two .container blocks, which is already formatted in CSS, I have in each container a a element that will add a class to the .option-box div, the problem arises when I click on only a a element and jQuery adds the classes to the .option-box of the other .container , causing two menus to appear.

Javascripts below:

$(function optionbox() {
  var box = $('.container .option-box');
  var button = $('.container a.button');
  button.on('click', function optionbox(){
    box.toggleClass('show');
  });
});

How to make jQuery handle the element of only a .container ?

    
asked by anonymous 15.10.2014 / 21:12

1 answer

2

You will have to start from the clicked element and "search" in the DOM to find the element you want.

Using the .closest () can go up in the DOM from the clicked element and then .find () to get down to the element you want.

Example:

$(function optionbox() {
    var box = $('.container .option-box');
    var button = $('.container a.button');
    button.on('click', function optionbox() {
        $(this).closest('.container').find('.option-box').toggleClass('show');
    });
});

jsFiddle: link

Like @Jader suggested , a simpler variant would only be

$(this).siblings('.option-box').toggleClass('show');

This is because <div class="option-box"> is sibling of .button .

Another variant is still using .next ()

$(this).next().toggleClass('show');

Example: link

    
15.10.2014 / 21:14