user3216573
user3216573

Reputation: 31

Javascript Table Iteration

I have an x-y table called "num", and I am trying to iterate through the table and obtain the numerical values in the cells. The alert keep showing me "undefined", and I don't know why. I've tried the innerHTML function, but it doesn't give me the value I need. Any help would be appreciated (I'm new to Javascript).

 var x=0;
 var y=0;
 var table=document.getElementById("num");

    for (var r = 1, n = table.rows.length; r < n; r++) {

        x= table.rows[r].cells[0].value;
        y= table.rows[r].cells[1].value;
        alert(x);

    }

Upvotes: 0

Views: 84

Answers (2)

RobG
RobG

Reputation: 147413

> x= table.rows[r].cells[0].value

Table cells (td and th elements) don't have a default value property. If you wish to get the text content of a DOM element, you can use the W3C textContent property or the IE innerText property depending on which one is supported in the host. Browsers support one or the other, some both, so you can do:

var cell;
...
cell = table.rows[r].cells[0];
x = cell.textContent || cell.innerText;

You can also write a small function to do the job:

function getText(el) {
  if (typeof el.textContent == 'string') {
    return el.textContent;
  } else if (typeof el.innerText == 'string') {
    return el.innerText;
  }
}

Then you can just do:

x = getText(table.rows[r].cells[0]);

Note that the value of x will be a string, so be careful if you intend using the + operator for addition.

Upvotes: 1

helion3
helion3

Reputation: 37401

You'll want .innerText instead of innerHTML

.value is for form elements like inputs.

Upvotes: 0

Related Questions