2021年4月10日星期六

Get a specific row from specific table with JavaScript?

Say my dynamic HTML looks something like this:

<table id="DanishCompanies">    <tr><th>Name</th><th>Employees</th><th>Founded</th></tr>    <tr id="19"><td>Company A</td><td>80</td><td>1980</td></tr>    <tr id="17"><td>Company B</td><td>12</td><td>1910</td></tr>    <tr id="26"><td>Company C</td><td>5000</td><td>2015</td></tr>  </table>  <table id="SwedishCompanies">    <tr><th>Name</th><th>Employees</th><th>Founded</th></tr>    <tr id="10"><td>Company D</td><td>500</td><td>1950</td></tr>    <tr id="12"><td>Company E</td><td>900</td><td>1990</td></tr>    <tr id="17"><td>Company F</td><td>90</td><td>2010</td></tr>  </table>  <table id="NorwegianCompanies">    <tr><th>Name</th><th>Employees</th><th>Founded</th></tr>    <tr id="17"><td>Company G</td><td>105</td><td>1970</td></tr>    <tr id="18"><td>Company H</td><td>100</td><td>1980</td></tr>    <tr id="19"><td>Company I</td><td>45</td><td>2000</td></tr>  </table>  

Each tr has ID, but ID only relatively unique to the table, as other tables might have the ID, and the number of rows might vary.

How would I obtain the founding year (column 2) of a Swedish company with id of 17?

I would imagine you would do it like this but I fail to find the correct code.

var table = document.getElementById("SwedishCompanies");  var row_index = ??? //should return 2  return table[row_index].cells[2].innerHTML;  

I can't use getElementById just to get id "17", because I would risk getting Danish or Norwegian's company because the order of these tables is random.

https://stackoverflow.com/questions/67040785/get-a-specific-row-from-specific-table-with-javascript April 11, 2021 at 09:51AM

没有评论:

发表评论