the HTML below
<div class="commentlinks">
<a class="commentlinked blogcount">3</a>
<a class="commentlinked fbcount">2</a>
<a class="commentlinked disqcount">1</a>
<a class="allcommentcount"></a>
</div>
with this jQuery
$('.commentlinks').each(function() {
var currentValue = parseInt($(".blogcount").text());
var currentValue2 = parseInt($(".fbcount").text());
var currentValue3 = parseInt($(".disqcount").text());
var newValue = currentValue + currentValue2 + currentValue3;
$(".allcommentcount").text(newValue);
});
Returns this successfully http://jsfiddle.net/hQzZQ/22/
3
2
1
6
but when i have this html
<div class="commentlinks">
<a class="commentlinked blogcount">3</a>
<a class="commentlinked fbcount">2</a>
<a class="commentlinked disqcount">1</a>
<a class="allcommentcount"></a>
</div>
<div class="commentlinks">
<a class="commentlinked blogcount">7</a>
<a class="commentlinked fbcount">6</a>
<a class="commentlinked disqcount">1</a>
<a class="allcommentcount"></a>
</div>
It Returns http://jsfiddle.net/hQzZQ/23/
3 2 1 74
7 6 1 74
why is it returning it incorrectly help me fix it please!
You have to use
findorchildrento select the elements in the current context. Also, useparseInt(.., 10)to parse numbers.Demo: http://jsfiddle.net/sym7H/
If your document is well-structured, you can also use
.children("a")to find the elements, then use.eq(..)or.slice(.., 1)to select the elements. This has an improved efficiency.Demo: http://jsfiddle.net/sym7H/1/