Bri.H.
Bri.H.

Reputation: 313

NodeList operations

I got set of divs with integer values (always) unfortunately only with class (cannot add id because they are generated in a loop by other app i cannot mess with)

<div class="aaposition">3</div>
<div class="aaposition">4</div>
<div class="aaposition">5</div>
<div class="bbposition">30</div>
<div class="bbposition">30</div>
<div class="bbposition">30</div>

So i'm creating two nodelists (good that both lists got exact length).

aalist = document.getElementByClassName('aaposition');
bblist = document.getElementByClassName('bbposition');

What i need to do is to sum results of multiplying aaitem[i] with bbitem[i] and show it somewhere

sumlist = 0;
for (i = 0; i < aalist.length; i++) {
   sumlist += aalist[i] * bblist[i];
}
showdiv.innerHTML = sumlist;

But i don't know how to pick those values from nodelist, how can i pick the value i'm interested in? Is it .innerHTML, .value or what? All i found was style examples (.style.background ... etc.).

Also do i need to parse into integer? Do i need to convert NodeList to array?

Upvotes: 0

Views: 809

Answers (1)

Simon Staton
Simon Staton

Reputation: 4505

You need to use document.getElementsByClassName and also fix the typo for .length you also need to call the nodes .innerHTML...

var result = document.getElementById('result'),
    aalist = document.getElementsByClassName('aaposition'),
    bblist = document.getElementsByClassName('bbposition'),
    sumlist = 0;

for(var i=0; i<aalist.length; i++) {
   sumlist += aalist[i].innerHTML * bblist[i].innerHTML;
}

result.innerHTML = sumlist;

Working jsfiddle

Upvotes: 2

Related Questions