How to control classes individually in jQuery?

Asked

Viewed 82 times

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 blocks .container, which is already formatted in CSS, I have in each container an element a that will add a class to the div .option-box, the problem arises when I click on only one element a 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 get jQuery to manipulate the element of just one .container?

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 the .find() to descend to the element that wants.

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: http://jsfiddle.net/cs6erreu/

Like the @Jader suggested, a simpler variant would be only

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

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

Another variant is to use the .next()

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

Example: http://jsfiddle.net/cs6erreu/1/

  • 1

    It worked, thank you very much for your help!

  • @Isacfadoni added two more options. If your HTML is like in the example they are even better...

  • 1

    I tested the other solutions too, and it worked perfectly. Again thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.