Question
How do you select text node values identified with a specific attribute (background color #00FF00)?
As I'm new to javascript, I'm not sure how to do the first step:
- use the js dom to select the node with 00FF00
- split the string with " " as the separator
- loop through and add each split[2] with +=
- write the sum (240+80+600) to html
Code
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
var data = document.getElementsByTagName('span');
document.write(data);
};
</script>
</head>
<body>
<div class="box">
<span class="highlight">Dave collected 700 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 240 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 80 items.</span>
</div>
<div class="box">
<span class="highlight" style="background-color:#00FF00;">Bob collected 600 items.</span>
</div>
</body>
</html>
var els = document.querySelectorAll('span.highlight');
var len = els.length;
//console.log(len); //returns 4
var total = 0;
for (var i=0; i < len; i++) {
if (els[i].style.backgroundColor.toLowerCase() === 'rgb(0, 255, 0)') {
var txt = els[i].innerHTML;
//split txt into array
split = txt.split(" ");
total += parseInt(split[2]);
}
}
console.log(total);