1

I HAVE

<tr>
<td nowrap="" align="right" id="n_852" class="tab ">1</td>
<td nowrap="" align="right" id="n_853" class="tab ">2</td>
<td nowrap="" align="right" id="n_854" class="tab ">3</td>
<td nowrap="" align="right" id="n_855" class="tab ">4</td>

</tr>

In js Can loop through out array n_i and calculate the total 1+2+3+4

thanks

2 Answers 2

3

http://jsfiddle.net/ZBLzp/

You could make it more restrictive by changing * to td

var elements=document.getElementsByTagName("*"),
    partial = new RegExp('n_','g'),
    total = 0;

for(var i=0; i< elements.length;i++){
    if(elements[i].id.match(partial)){
        total+= parseInt(elements[i].innerHTML);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

3
function doSum()
{
  var stillGoing = true;
  var sum = 0;
  var i = 852;
  while (stillGoing)
  {
    var element = document.getElementById('n_' + i);
    if (element != null)
    {
      sum += parseInt(element.innerHTML);
    }
    else
    {
      stillGoing = false;
    }
    i++;
  }
  return sum;
}

3 Comments

-1 Assumption that there are no gaps is a poor one. Also it doesn't work (even if you start at 852).
Sorry. Question originally started with n_0. But whatever index you start with should be irrelevant. Code base provided seems to imply no gaps, though it is an assumption, it doesn't seem to be a poor one considering the information given.
yes,sorry for update the question,However it should better if dont care about the init i

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.