Reputation: 83
So i have an array of divs. each div contains three span elements. Each span element can contain any number of digits.
This is what i have so far:
var arrayOfDivs = $(".avgMaxClass");
$.each(arrayOfDivs, function (index, value) {
});
what i want to do is calculate the total length of all the text within all the spans within the div im iterating through. I can't figure it how to do that.
EDIT: To be clear i don't want the total text length of all the divs. I want the text length of the current div that im iterating through
Upvotes: 0
Views: 202
Reputation: 22487
$(".avgMaxClass span").text().length;
Edit:
As you stated in your comment that you want to know the length for each DIV, here is another way using jQuery.each()
:
var avgMaxClass = $('.avgMaxClass');
$.each(avgMaxClass, function(i,item) {
// Output span text length for each item
console.log($("span", item).text().length);
});
Upvotes: 4
Reputation: 59292
Just iterate over the div and find its length.
$(".avgMaxClass").each(function(){
var thisDivsLength = $(this).find('span').text().length;
alert("Current div's length: " + thisDivsLength);
});
$.each
is for non-jQuery objects. Use $.fn.each
instead.
Upvotes: 2
Reputation: 48337
You can use a selector to get the div
s and span
s at the same time, or to split the logic and show both parts individually, you can use two selectors and loop over the results of each.
var total = 0;
$(".avgMaxClass").each(function(index, value) {
$(value).find("span").each(function(cindex, child) {
total += $(child).text().length;
});
});
$("#result").text("Total length: " + total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="avgMaxClass">
<span>1</span>
<span>12</span>
<span>123</span>
</div>
<div class="avgMaxClass">
<span>1234</span>
<pre>12345</pre>
<span>12345</span>
</div>
<div class="avgMaxClass">
<span>123456</span>
<span>1234567</span>
<span>12345678</span>
</div>
<div id="result"></div>
Upvotes: 2