Ethan
Ethan

Reputation: 817

Jquery : Get parent element then apply css selector to it

I am trying to figure out the best way to go about this. I am trying to expand/collapse all hide-able divs on a page. Which generally is no problem, however, I have four separate sections which require the expand/collapse to work independently. So, I am hoping to not have to write four separate scripts using four separate ids as selectors.

I found that this

$(function() {
    $('.expand').click(function() {
        $('#test *').nextAll('.silent').slideToggle();
    });
});

Works beautifully, so long as I only need to expand one section. So, my thought is this : If I can use jquery to get the parent div ( parent containing the expand button) class or id (as they'll each be different by necessity) and then apply the selector * class to it before executing a nextAll, that should solve my problem.

Here's a simple fiddle of what I have so far, in case you'd like further clarification. The goal is to be able to use the "expand" button for each section to expand the sections underneath, without expanding the other. (With a single script) jsfiddle

Thank you in advance for any assistance you might be able to provide.

Upvotes: 0

Views: 216

Answers (3)

fedmich
fedmich

Reputation: 5381

I've played around and created something quickly for you now :) http://jsfiddle.net/fedmich/6Rxzg/

It's different from your code but you could see a simple one.

You can use closest() to get the parent matching your CSS pattern. and you should probably use classnames instead of id

<div class="expander">
   ...content...
</div>
<div class="expander">
   ...content...
</div>

Some tips:

  1. Indent your code and put comments on it.
  2. rather than do a YELL or SILENT, use simple meaningful names like "shown"
  3. Please read the jsfiddle carefully, so you could apply styles like cursor:hand, don't forget to put enough spacing,
  4. only expand those that aren't expanded yet, etc

Some more tips:

  1. You could also put icons like + or - to show collapsed or NOT like what I did on my resume page before http://fedmich.com/resume/#work4

Sorry for the long answer. Doing accordions like this is always FUN to do! So don't forget to have lots of it!

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Add some class on div's with id test and then it will be more simple.

<div id="test" class="SomeClass">
content here
</div>

<div id="test2" class="SomeClass">
content
</div>

try with closest(), it will get the parent element whose id is test and then get child element of test with class silent and slide it:

$('.expand').click(function() {
        $(this).closest(".SomeClass").find('.silent').slideToggle();
    });

WORKING FIDDLE

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

Yes. Use:

$('.expand').click(function(){
    $(this).parent().find('.silent').slideToggle();
});

Demo

Upvotes: 3

Related Questions