Target individual class instance

I use css to hide the content that I want to reveal when a person clicks a link. There are several instances on the page.

I set an example, but currently clicking any of the links shows all the content.

http://jsfiddle.net/paulyabsley/rHD43/

thanks

+8
jquery
source share
4 answers

Use .siblings() to find the element with the details class, which is a sibling of the parent link element.

 $('.item h3 a').click(function () { $(this).parent().siblings(".details").toggleClass("display"); });​ 

Demo

+7
source share

Try this instead:

 $('.item h3 a').click(function () { $(this).parent().next().toggleClass("display"); });​ 

Demo is here .

What your current selector does is select all the elements that match. What the above snippet does is select the element with respect to the one that was pressed using $(this) , which in this case was pressed <a> .

Since <a> is inside <h3> and <div> is the brother of <h3> , not <a> , you need to use $.parent() to select <h3> , then use $.next() to get the next element after <h3> , which is the <div> that you want to switch.


The best way to do this is to attach a click handler to <h3> . This simplifies the selector chain and also fixes any problems that may occur with the <a> tag. This will work better IMO:

 $('.item h3').click(function () { $(this).next().toggleClass("display"); });​ 
+2
source share

You can go to the root element and search for details.

 $(this).parent().parent().find('.details').toggleClass("display"); 
+2
source share

A slightly more complicated solution, but it provides functionality for closing other descriptions when you open a new one, which, as I see it, is missing from the current answers.

 $('.item h3 a').click(function () { // always try cache your selectors if you plan on using them repeatedly. var $details = $(this).parent().next("div.details"); if ($details.hasClass('display')){ // if the item we clicked on is already displayed - we want to hide it. $details.toggleClass("display"); }else{ // now we want to close all other open descriptions $("div.details").removeClass("display"); // and only display the one we clicked on. $details.toggleClass("display",true); } });​ 

Working example

Animated example

0
source share

All Articles