Reputation: 1435
I have an HTML table with rows similar to this one:
<tr>
<td>11/05/2013</td>
<td>CBC W/DIFF</td>
<td> </td>
<td> <content ID="result210">Wbc: 4.5 X10E3/UL</content> </td>
<td>Final</td>
</tr>
I want to get the nodeValue "Wbc: 4.5 X10E3/UL"
Here is my javascript code so far:
var table = section.getElementsByTagName("table")[0];
var tablebody = table.getElementsByTagName("tbody")[0];
var rows = tablebody.getElementsByTagName("tr");
for (i=0; i<rows.length; i++) {
var cells = rows[i].getElementsByTagName("td");
var date = cells[0].childNodes[0].data;
var panel = cells[1].childNodes[0].data;
var result = cells[2].childNodes[0].data;
var description = cells[3].childNodes[0];
var content = description.firstChild.nodeValue; //SCRIPT5007: Unable to get property 'nodeValue' of undefined or null reference
var status = cells[4].childNodes[0].data;
console.log(date +" " +panel +" " +result +" " +content +" " +status);
}
Reported error is "SCRIPT5007: Unable to get property 'nodeValue' of undefined or null reference"
If I comment out the description and content parts, the other fields are reported correctly so I know I'm close. I have also tried:
var content = description.firstChild.firstChild.nodeValue; //SCRIPT5007: Unable to get property 'firstChild' of undefined or null reference
var content = description.getElementsByTagName("content").childNodes[0].nodeValue; //SCRIPT438: Object doesn't support property or method 'getElementsByTagName'
Any suggestions?
Upvotes: 0
Views: 2894
Reputation: 382092
The first child node is a text node, due to your space in
<td> <content ID="result210">Wbc: 4.5 X10E3/UL</content> </td>
What you want is to get the first child element :
var content = cells[3].children[0].innerHTML;;
More generally, you shouldn't use nodes most of the times, as it's hard to be sure there isn't a space or new line.
Note also that it's rare to dive into the elements like this : using classes and query based selection functions, you can get a more reliable and readable code. Here, as you have an id, you should simply do
var content = document.getElementById("result210").innerHTML;
Your question isn't clear on that point : I hope you don't have elements with such id on more than one row (an id can't be given to more than one element). Supposing you have a class instead, this would be
var content = rows[i].getElementsByClassName("result210").innerHTML;
Upvotes: 3