Obeck
Obeck

Reputation: 67

How distinguish between same class name

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().lengthyou get the number of elements in all jQuery objects. jsfiddle

Upvotes: 0

Views: 344

Answers (3)

kapantzak
kapantzak

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

Sudharsan S
Sudharsan S

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) 
});

Fiddle

Upvotes: 1

Rory McCrossan
Rory McCrossan

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);
});

Updated fiddle

Note that I used eq() to relate the current p element to the matching span element.

Upvotes: 1

Related Questions