Note that there are some explanatory texts on larger screens.

plurals
  1. POSelect Nodes & Sum values
    text
    copied!<h2>Question</h2> <p>How do you select text node values identified with a specific attribute (background color #00FF00)?</p> <p>As I'm new to javascript, I'm not sure how to do the first step:</p> <ol> <li>use the js dom to select the node with 00FF00</li> <li>split the string with " " as the separator</li> <li>loop through and add each split[2] with +=</li> <li>write the sum (240+80+600) to html</li> </ol> <h2>Code</h2> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script&gt; window.onload = function() { var data = document.getElementsByTagName('span'); document.write(data); }; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="box"&gt; &lt;span class="highlight"&gt;Dave collected 700 items.&lt;/span&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;span class="highlight" style="background-color:#00FF00;"&gt;Bob collected 240 items.&lt;/span&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;span class="highlight" style="background-color:#00FF00;"&gt;Bob collected 80 items.&lt;/span&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;span class="highlight" style="background-color:#00FF00;"&gt;Bob collected 600 items.&lt;/span&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><br /></p> <pre><code>var els = document.querySelectorAll('span.highlight'); var len = els.length; //console.log(len); //returns 4 var total = 0; for (var i=0; i &lt; 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); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload