Ashik Basheer
Ashik Basheer

Reputation: 1601

FInd a span's text which itself is dynamically generated

I have a DIV which is dynamically created using jQuery.

<div id="post-1">
<ul class="action-bar"> 
<li>
    <span class="likepostval" id="likecount-113">35</span></span>
    <span class="likepost">like</span>
</li>  
<li><a class="muted">6 days</a></li>  
</ul>
</div>

There are several such div with IDs post-2, post-3 and so on... I'm using the following jQuery script to fetch .likepostval's id and text.

$(document).on('click','.likepost',function(){
var id = $(this).closest('.likepostval').attr('id');
var text = $(this).closest('.likepostval').text();
});

For the above script the console says 'Undefined'. Where am I going wrong ?

Upvotes: 0

Views: 70

Answers (1)

Faust
Faust

Reputation: 15404

.closest returns the nearest ancestor element matching the selector. What you want is a sibling:

var id = $(this).siblings('.likepostval').attr('id')

...Etc.

Also note: you have an extra closing span in there.

Upvotes: 4

Related Questions