So I have this code (from the gracious help from this site!)
window.onload = function inventorytable() {
var tableRows = document.getElementById
("inventorytable").getElementsByTagName("tbody")[0].getElementsByTagName("tr");
Now from here, I want to get all of the TDs, under all of the TRs. I also want to be able to perform operations on the TDs, depending on which TD (i.e. which column) they are in the table.
So for example, if I have
<tr>
<th>Processor Speed</th>
<th>Amount of RAM</th>
<tr>
<td>2.0</td>
<td>3.0</td>
</tr>
<tr>
<td>3.2</td>
<td>4.0</td>
</tr>
I want to be able to select each TD separately, depending on its order within the TR, and then add text to it. There will be a variable number of TRs, at least 20, and possibly more. There are going to be about 10-15 TDs.
The text added would be something like ” Ghz” or ” GB”
You have to iterate over all
trelements (which is aNodeList[MDN], returned fromgetElementsByTagName[MDN]):Inside the loop you can get all
tds of one row again withgetElementsByTagNameor using the.cells[MDN] property. You can then decide to either iterate over them as well or to access the specific cells explicitly, such ascells[1]to access the second cell (second column) in that row.If the cells contain simple text or you don’t have any event handlers bound to their descendants, you can simply use
innerHTML[MDN] to change the element’s text content.Otherwise you have to create a new text node and append it to the cell (that might be the best option in any case).
The Mozilla Developer Network is a great source for all kinds of information, including the DOM and JavaScript.