Reputation: 63
I have this structure:
<div class="list">
<ul>
<li>
<span class="number">1</span>
<p class="list-title"><a href="#">Welcome</a></p>
<img src="images/like.png" class="like" />
<div class="subcomments">
<div class="comments">
<ul>
<li>
<span class="number">2</span>
<img src="images/like.png" class="like" />
</li>
</ul>
</div>
</div>
</li>
</ul>
And I want when click on the class "like" appears the content of span.number, i.e. goes to the father and gets the content of the span with class number.
I'm trying this:
$('.like').parent().children('span:first').text()
But always gives me 1 in the two situations, instead of giving 1 in the first like, and 2 in the second like.
Upvotes: 6
Views: 13128
Reputation: 38147
Use .siblings()
:
$('.like').siblings('span:first').text();
This in itself will always show 1 - because the selector .like
is returning 2 elements - with the following code (.siblings('span:first').text();
) running against the first element both times - you need to use each to loop each values :
$('.like').each(function() {
alert($(this).siblings('span:first').text());
})
Upvotes: 1
Reputation: 9277
you should use this
$(.link).click(function() {
$(this).parent().find('.number').text();
// $(this).parent().find('span:first').text(); // same thing
// $(this).closest('.number').text(); // same thing
})
when you just write $('.link').parent().find('span:first').text()
;
it always will take first .link
class and take its span value, when you use this
it uses exactly that .link
that you have clicked on
Upvotes: 0
Reputation: 148180
You need jquery siblings(),
$('.like').siblings('span:first').text();
Upvotes: 4