Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

javascript - Access rows from different tables using row IDs

Suppose I have two different tables as below:

<table id="T1">
  <tr id="a">
    <td>a</td>
  </tr>
  <tr id="b">
    <td>b</td>
  </tr>
</table>

<table id="T2">
  <tr id="a">
    <td>A</td>
  </tr>
  <tr id="b">
    <td>B</td>
  </tr>
</table>

These two tables have different IDs. However, due to design, some of their rows, when created, have the same IDs. In this case, both rows have the same ids a and b.

I am having trouble accessing rows by using document.getElementById since it could be multiple duplication. How do I specify a row using both the table ID and the row ID in JavaScript? Thanks.

question from:https://stackoverflow.com/questions/65884246/access-rows-from-different-tables-using-row-ids

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should never ever use the same ID twice! That said, you can use document.querySelectorAll() where you can use the same selectors as you use in CSS. Something like so to get all <tr>

var rowsOfTable1 = document.querySelectorAll('#T1 tr');
var rowsOfTable2 = document.querySelectorAll('#T2 tr');

rowsOfTable1.forEach( row => { console.log(row.innerHTML) });
rowsOfTable2.forEach( row => { console.log(row.innerHTML) });
<table id="T1">
  <tr id="a">
    <td>T1 a</td>
  </tr>
  <tr id="b">
    <td>T1 b</td>
  </tr>
</table>

<table id="T2">
  <tr id="a">
    <td>T2 A</td>
  </tr>
  <tr id="b">
    <td>T2 B</td>
  </tr>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...