I am trying to pull a specific value from the HTML of a cell in an HTML table. I have tried to use the .rows parameter, which didn’t work (the JavaScript didn’t run past the line that used .row
) and I have currently settled on adding an id
to the rows that I want to pull from, accessing those rows using getElementById()
, and then trying to use children[]
and innerHTML
to get the value that I’m looking for. Below is my example code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
var hits = document.getElementById("B2").children[4].innerHTML
alert(hits)
</script>
</head>
<body>
<table id="battingTable">
<caption>Batting</caption>
<tr>
<th>Player</th>
<th>G</th>
<th>AB</th>
<th>R</th>
<th>H</th>
<th>2B</th>
<th>3B</th>
<th>HR</th>
<th>RBI</th>
<th>BB</th>
<th>SO</th>
<th>AVG</th>
<th>OBP</th>
<th>SLG</th>
<th>OPS</th>
</tr>
<tr id="B2">
<td>Player1</td>
<td></td>
<td>5</td>
<td></td>
<td>2</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>
However, this technique also appears to fail, since a JavaScript alert doesn’t even show up on my page, let alone display the correct value (5
).
Is there another technique that I can use to access the value I am looking for? (My end goal is to access the two values in this table, divide one by the other, and then set another cell in the table to display that final calculated value.)
2
Answers
Your code is running, but it runs before most of the content loads, since it is in the
<head>
element. By moving it to the end of<body>
, it will run the script after everything loads.You don’t need id’s. Just simply put the JavaScript codes at the end of the
body
. And it will work.And also you need to put a semicolon
;
after each JS statement.