Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery iterate through elements

I have the following HTML.

<div id="price_list">
 <input type="text" value="100" class="input_price" />
 <input type="text" value="256" class="input_price" />
 <input type="text" value="500" class="input_price" />
 <input type="text" value="04.26" class="input_price" />
 <input type="text" value="156" class="input_price" />
 <input type="text" value="052" class="input_price" />
 <input type="text" value="692" class="input_price" />
 <input type="text" value="25.36" class="input_price" />
 <input type="text" value="10.56" class="input_price" />
</div>

What is the best way to get the SUM of values of the elements having class input_price?

Please note that I am concerned about the performance. My actual HTML is bit more complex (sometimes I have thousands of elements). I tried using .each() but sometimes my browser gets stuck. So that the question can be modified to "What is the best way to iterate through elements TO GET some data?"

My try:

var total = 0;

$(".input_price").each(function(){
  total+=parseFloat($(this).val());    
});
like image 889
Red Avatar asked Mar 12 '26 00:03

Red


1 Answers

Just because you care about performance, use pure JavaScript and a single for loop:

var list = document.getElementById("price_list"),
    inputs = list.getElementsByTagName("input"),
    total = 0;

for (var i = 0, len = inputs.length; i < len; i++) {
    total += +inputs[i].value;
}

console.log(total);
like image 146
VisioN Avatar answered Mar 14 '26 12:03

VisioN