Reputation: 67
There are endless divs with same class name. In my example with class="box"
and I will evaluate how many letters are in the respective box. With $( ".box p" ).text().length
you get the number of elements in all jQuery objects. jsfiddle
Upvotes: 0
Views: 344
Reputation: 11750
Use each()
function to loop through these elements and return the text length
Check the DEMO
$('.box').each(function(index) {
var count = parseInt(index) + 1;
$('body').append('<div>Box ' + count + ': <span>' + $(this).children('p').text().length + ' Letter</div>');
});
Upvotes: 1
Reputation: 15393
Use .each()
to iterate all p tags text and .eq()
to get index of the span and append the text length using .html()
into the span
$( ".box p" ).each(function(index) {
$("span").eq(index).html($(this).text().length)
});
Upvotes: 1
Reputation: 337560
You need to loop over each p
element and count the length of the text()
individually. Try this:
$(".box p").each(function(i) {
var n_letter = $(this).text().length;
$("span").eq(i).text(n_letter);
});
Note that I used eq()
to relate the current p
element to the matching span
element.
Upvotes: 1