[英]Javascript: Find value of an element in tag by classname
我有以下代碼:
<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>
class="Pattern"
即“幾何分解”和“管線class="Pattern"
來獲取標簽span
值的方法。 我可以使用indexOf
...之類的JavaScript函數,但我一直在尋找一種更優雅的方式來解決此問題,方法是使用標簽名稱來調用標簽。 document.querySelector('.pattern')
或者比這更具體
document.querySelector('span.Pattern')
getElementsBy *方法返回HTMLCollections,這可能很難使用。 當您需要集合時,可以考慮使用querySelectorAll,它返回一個靜態NodeList-與HTMLCollection不同,它可以直接迭代,在迭代時不會更改,並且更加靈活。
或者,當您僅選擇一個元素時,只需使用.querySelector。
另一個注意事項:除非要特別獲得HTML標記,否則通常使用.textContent
而不是.innerHTML
。
您可以使用函數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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.