Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

targeting specific jQuery element with identical class name [duplicate]

Tags:

jquery

Possible Duplicate:
How to select an element by class inside “this” in Jquery

I'm newer to jQuery...I think this has something to do with using a 'this" command but not sure.

I have a page that is programmatically creating several divs like this:

<div class="moreinfolink">Click For More Information
<div class="moreinfotext">Additional Info Here</div>
</div>

So there are several .moreinfolink and .moreinfotext classes on a page.

I used this code to toggle showing the moreinfotext div:

$('.moreinfolink').click(function() {
  $('.moreinfotext').toggle('slow', function() {
  });

But this obviously does a toggle for ALL of the moreinfotext divs that exist on the page.

Two questions: How can I do it for the specific child div that is inside the parent moreinfolink div? Is there a better way to do it than the direciton I'm going?

Thanks!

like image 825
Chris Cummings Avatar asked Jan 01 '12 23:01

Chris Cummings


2 Answers

You could use .find (as @FelixKling suggests):

$('.moreinfolink').click(function() {
    $(this).find('.moreinfotext').toggle('slow', function() { ... });
});

Example: http://jsfiddle.net/hejFq/

like image 139
Andrew Whitaker Avatar answered Oct 20 '22 01:10

Andrew Whitaker


This fiddle shows you how to do it: http://jsfiddle.net/ZAwTL/

Or this fiddle, which shows calling the find() method directly as Felix Kling suggests.

Sample HTML

<div class="moreinfolink">Click For More Information
<div class="moreinfotext">Additional Info Here</div>
</div>
<br>
<br>
<div class="moreinfolink">Click For More Information
<div class="moreinfotext">Additional Info Here</div>
</div>
<br>
<br>
<div class="moreinfolink">Click For More Information
<div class="moreinfotext">Additional Info Here</div>
</div>

JavaScript

$('.moreinfolink').click(function() {
  $(this).find('.moreinfotext').toggle('slow', function() { });
});
like image 34
Tim M. Avatar answered Oct 20 '22 01:10

Tim M.