unebune
unebune

Reputation: 87

jQuery - select div at same level

I want to select a specific div, when clicking on a button... The only issue is, it has to be the div of the buttonClicked's parent div... Sample:

 <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>

Code:

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

Any suggestions ? :-)

Upvotes: 8

Views: 35617

Answers (5)

Guillermo Guti&#233;rrez
Guillermo Guti&#233;rrez

Reputation: 17859

Try:

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

Upvotes: 0

mathius1
mathius1

Reputation: 1391

First of 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");
}

Upvotes: 1

Sunny R Gupta
Sunny R Gupta

Reputation: 5136

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

Also, the following code works too:

$(".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>

Took the liberty to add the following css:

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

JSFiddle for the above sample

Upvotes: 3

Smeegs
Smeegs

Reputation: 9224

This should do it.

.closest will go up through the parents until it finds a match. Then from that you can .find the target div that you are looking for.

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

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

Upvotes: 17

Eduardo Quintana
Eduardo Quintana

Reputation: 2388

Using

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

This will select the parent div of the parent div where the button is.

Upvotes: 3

Related Questions