我有以下代码:
<tr style="background: rgb(243, 236, 236);">
<td style="width:20%;">1:0</td>
<td style="width:70%;"><span><i class="glyphicon glyphicon-random"></i></span><span class="Pattern">Geometric Decomposition</span></td>
<td style="width:10%;">1</td>
</tr>
<tr>
<td style="width:20%;">1:11</td>
<td style="width:70%;"><span><i class="glyphicon glyphicon-road"></i></span><span class="Pattern">Pipeline</span></td>
<td style="width:10%;">1</td>
</tr>
更新
我正在迭代表行以获取 class="Pattern"
中的值同时还读取第一个单元格的值(ID 例如 1:01
)。我当前的 JavaScript 代码:
nodeIds = []
nodePatterns = []
for(i = 0; i < tds.length; ++i) {
var cells = tds[i].getElementsByTagName("td");
nodeIds.push(cells[0].innerHTML);
nodePatterns.push(cells[1].innerHTML);
}
但与 cells[1].innerHTML
我刚刚得到以下值:
-
<span><i class="glyphicon glyphicon-random"></i></span><span class="Pattern">Geometric Decomposition</span>
-
<span><i class="glyphicon glyphicon-road"></i></span><span class="Pattern">Pipeline</span>
现在我正在寻找一种方法来获取标签span
的值与class="Pattern"
即几何分解和管道。我可以使用像indexOf
这样的javascript函数...但我一直在寻找一种更优雅的方法来解决这个问题,通过使用标签名称调用标签。
他们是一种方法吗?
最佳答案
您可以使用函数querySelector
选择第一个找到的元素。
console.log(document.querySelector('table tr td span.Pattern').textContent)
.as-console-wrapper { max-height: 100% !important; top: 0; }
<table>
<tbody>
<tr>
<td style="width:70%;">
<span><i class="glyphicon glyphicon-random"></i></span>
<span class="Pattern">Geometric Decomposition</span>
</td>
</tr>
</tbody>
</table>
如果您需要访问多个span
元素,可以使用函数 querySelectorAll
返回找到的元素的 NodeList。
要获取第一个TD,可以使用函数closest
向上,然后执行函数querySelector
。
Array.prototype.forEach.call(document.querySelectorAll('table tr td span.Pattern'), function(span) {
console.log(span.closest('tr').querySelector('td').textContent);
console.log(span.textContent);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
<table>
<tbody>
<tr style="background: rgb(243, 236, 236);">
<td style="width:20%;">1:0</td>
<td style="width:70%;"><span><i class="glyphicon glyphicon-random"></i></span><span class="Pattern">Geometric Decomposition</span></td>
<td style="width:10%;">1</td>
</tr>
<tr>
<td style="width:20%;">1:11</td>
<td style="width:70%;"><span><i class="glyphicon glyphicon-road"></i></span><span class="Pattern">Pipeline</span></td>
<td style="width:10%;">1</td>
</tr>
</tbody>
</table>
关于Javascript:按类名查找标签中元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49418589/