我有以下 HTML。如何在 JavaScript 中获取 tr class="status_visible"
下的 TD
内容?我在下面的代码中突出显示了我感兴趣的 td
。可能有多个 status_visible
行。我只对第一行感兴趣。
没有id
,所以我无法使用getElementById()
。 (我也不能使用 jQuery)
<table class="colored">
<thead>
<tr>
<th colspan="9">
<h2>History</h2>
</th>
</tr>
<tr>
<th>Value</th>
<th>Change Reason</th>
<th>Changed By</th>
<th>Changing Environment</th>
<th>Change Date (UTC)</th>
</tr>
</thead>
<tbody>
<tr class="status_visible">
<td>N</td> <!-- get this value -->
<td>CSS-ID: 343423</td>
<td>login_details</td>
<td>applicationname::signedinuser</td>
<td>2018-01-02 21:09:47 +0000</td>
</tr>
<tr class="status_hidden">
<td>Y</td>
<td>CSS-ID:5554</td>
<td>ServiceName</td>
<td></td>
<td>2014-02-19 13:37:50 +0000</td>
</tr>
</tbody>
</table>
最佳答案
使用document.querySelector()使用此选择器:
'tr.status_visible td:nth-child(n)'
…其中 n
是您感兴趣的 td
列(从 1 开始)。
例如,这将获取具有“status_visible”类的 tr
的第一个 td
的文本内容:
document.querySelector('tr.status_visible td:nth-child(1)').textContent
片段:
console.log(document.querySelector('tr.status_visible td:nth-child(1)').textContent);
<table class="colored">
<thead>
<tr>
<th colspan="9">
<h2>History</h2>
</th>
</tr>
<tr>
<th>Value</th>
<th>Change Reason</th>
<th>Changed By</th>
<th>Changing Environment</th>
<th>Change Date (UTC)</th>
</tr>
</thead>
<tbody>
<tr class="status_visible">
<td>N</td>
<td>CSS-ID: 343423</td>
<td>login_details</td>
<td>applicationname::signedinuser</td>
<td>2018-01-02 21:09:47 +0000</td>
</tr>
<tr class="status_hidden">
<td>Y</td>
<td>CSS-ID:5554</td>
<td>ServiceName</td>
<td></td>
<td>2014-02-19 13:37:50 +0000</td>
</tr>
</tbody>
</table>
关于javascript - 获取不带 "id"属性的 td 的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48067938/