Reputation: 2853
I'm trying to find the text of a span that is close to a div that I clicked. Right now, I'm getting nothing in console.log.
html:
<div class="section group">
<div class="col2 span_1_of_2 photo">
<img class="person" src="img/mobile/Bill.jpg" />
</div>
<div class="col2 span_1_of_2 details last">
<div class="quote">"When in the course of human events..."</div>
<div class="attribution"><span class="person_name">Bill</span>, <span class="person_age">89</span> <span class="person_where"></span></div>
</div>
</div>
jquery:
$('.person').on('click', function() {
//get name
var person_name = $(this).closest('.person_name').text();
console.log(person_name); //returns nothing
});
I haven't seen exactly this question before. Does anyone know what I'm doing wrong, please?
Upvotes: 0
Views: 3563
Reputation: 158
You got a traversal problem, you have to go up the DOM tree and then search down the DOM tree. sample:
$('.person').on('click', function() {
//get name
var person_name = $(this).parent().next().find('.person_name').text();
console.log(person_name); //returns Bill
});
Upvotes: 0
Reputation: 611
$('.person').on('click', function() {
//get name
var person_name=$(this).closest('div').siblings('.details').find('.person_name').text();
console.log(person_name);
});
Upvotes: 0
Reputation: 207901
.closest()
traverses up the DOM and .person-name
is the descendant of a sibling element. Instead use:
var person_name = $(this).parent().next().find('.person_name').text();
$('.person').on('click', function() {
//get name
var person_name = $(this).parent().next().find('.person_name').text();
console.log(person_name); //returns nothing
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section group">
<div class="col2 span_1_of_2 photo">
<img class="person" src="img/mobile/Bill.jpg" />
</div>
<div class="col2 span_1_of_2 details last">
<div class="quote">"When in the course of human events..."</div>
<div class="attribution"><span class="person_name">Bill</span>, <span class="person_age">89</span> <span class="person_where"></span>
</div>
</div>
</div>
Upvotes: 2