Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ? :-)

like image 892
unebune Avatar asked Feb 28 '14 21:02

unebune


People also ask

What is .next in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

What is prevObject in jQuery?

jQuery returns prevObject if the DOM does not have the element for which jQuery is being run. You might see the element in your source at the run-time however, it is not not bound to the DOM and therefore, it shows prevObject.

What is the use of siblings in jQuery?

The siblings() is an inbuilt method in jQuery which is used to find all siblings elements of the selected element. The siblings are those having same parent element in DOM Tree. The DOM (Document Object Model) is a World Wide Web Consortium standard. This is defines for accessing elements in the DOM tree.


2 Answers

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/

like image 190
Smeegs Avatar answered Oct 10 '22 11:10

Smeegs


Using

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

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

like image 30
Eduardo Quintana Avatar answered Oct 10 '22 10:10

Eduardo Quintana