JQuery - select a div at the same level

I want to select a specific div when I click on the button ... The only problem is that it should be a div from buttonClicked parent div ... Example:

 <div class="container">
   <div class="box">
     <h2>Langtidsparkering</h2>
     <div class="content">
       Lorem ipsum dolor sit amet..
     </div>
   </div>
   <div class="listcontainer">
     <div class="list"> (THIS DIV SHOULD GET A CLASS "VISIBLE", WHEN THE BUTTON IS CLICKED)
     </div>
     <div class="listbar">
       <button class="viewPrices" type="submit" title="Open">Se priser<span></span </button>
      </div>
    </div>
  </div>

the code:

    $(".viewPrices").click(function () {
         $(".viewPrices").parents('.listaccordion .list').toggleClass('visible');
});

Any suggestions?: -)

+4
source share
5 answers

That should do it.

.closestwill go through the parents until it finds a match. Then from this, you can .findtarget the div you are looking for.

$(".viewPrices").click(function () {
     $(this).closest('.listcontainer').find('.list').toggleClass('visible');
});

here is the updated fiddle: http://jsfiddle.net/n264v/2/

+4
source

Edited your JSFiddle: http://jsfiddle.net/n264v/3/

The following code also works:

$(".viewPrices").click(function () {
         $(".viewPrices").parent().siblings('.list').toggleClass('visible');
});

For this HTML:

<div class="container">
   <div class="box">
     <h2>Langtidsparkering</h2>
     <div class="content">
       Lorem ipsum dolor sit amet..
     </div>
   </div>
   <div class="listcontainer">
     <div class="list"> (THIS DIV SHOULD GET A CLASS "VISIBLE", WHEN THE BUTTON IS CLICKED)
     </div>
     <div class="listbar">
       <button class="viewPrices" type="submit" title="Open">Se priser<span></span </button>
      </div>
    </div>
  </div>

css:

.list{
    display:none;
}
.visible{
    display:block !important;
}

JSFiddle

+1

$(this).parent().parent().children("div:eq(0)").toggleClass('visible');

div div, .

0

Try:

$(".viewPrices").click(function () {
     $(this).closest('div').prev('div').toggleClass('visible');
});
0
source

Firstly, there is no div with the class "listaccordion", so you will never find a match.

You can use:

$(".viewPrices").click(function () {
$(this).parent(".listbar").siblings(".list").toggleClass("visible");
}
-1
source

Source: https://habr.com/ru/post/1529480/


All Articles