LauraNMS LauraNMS - 1 month ago 5
jQuery Question

jquery find text of nearest span with a certain class

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">&quot;When in the course of human events...&quot;</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?

Answer

@j08691 and @Wolfgang Criollo had it partly right - I had to go up to the parent. But here's how I had to get my specific element:

$(this).parent().first().find('.quote_box').find('.attribution').find('.person_name').text()
Comments