Reputation: 5601
So, I have the following php and js markup:
<div class="top" data-id="<?php echo $id; ?>">
<div class="middle">
Click
</div>
<div class="info"> <!--Note that I am targeting a child div -->
<div class="name">
Steve
</div>
</div>
</div>
Then for my js:
jQuery(document).on( 'click', '.middle', function(e) {
var my_id= jQuery(this).parent('.top').data("id");
});
At this point, when the middle
div is clicked, the js var my_id
is equal to the data_id
of its top parent div (with .top
).
Now, I want to save another div as below (simple html).
var my_name = $('.name').html();
How do I target the specific .name
class within the specific `data-id' div?
Upvotes: 1
Views: 45
Reputation: 1525
Use the parent and find methods.
var current;
$(document).on( 'click', '.middle', function(e) {
var my_id= $(this).parent('.top').data("id");
current = $(this).parent().find('.name');
console.log($(current).html());
});
Edit: John Crozier's answer is more complete. Beat me to it :)
Upvotes: 1
Reputation: 241128
You could use the .siblings()
method to select all the sibling elements of .middle
, and then use .find()
to find any descendant .name
elements:
jQuery(document).on( 'click', '.middle', function(e) {
var my_id= jQuery(this).parent('.top').data("id");
var my_name = jQuery(this).siblings().find('.name').html();
});
Upvotes: 3