我正在尝试遍历文档并获取元素的内容,以为我正在返回undefined
...
var el = document.querySelectorAll(".home .something .test");
var c = el.textContent;
alert(c);
https://jsfiddle.net/fevfymz1/
有人能看到什么出错吗?
答案 0 :(得分:2)
var c = el[0].textContent;
因为document.querySelectorAll()
返回匹配数组
var el = document.querySelectorAll(".home .something .test");
var c = el[0].textContent;
alert(c);

<div class="home">
<div class="something">
<table>
<tr>
<td>asdasd</td>
</tr>
<tr>
<td>
<span class="test">Alert this</span>
</td>
</tr>
<tr>
<td>asdasd</td>
</tr>
</table>
</div>
</div>
&#13;
答案 1 :(得分:0)
您需要使用loop
,因为document.querySelectorAll()
会返回array
。
var el = document.querySelectorAll(".home .something .test");
for (i = 0; i < el.length; i++) {
alert(el[i].textContent);
}
//var c = el.textContent;
//alert(c);
&#13;
<div class="home">
<div class="something">
<table>
<tr>
<td>asdasd</td>
</tr>
<tr>
<td>
<span class="test">Alert this</span>
</td>
</tr>
<tr>
<td>asdasd</td>
</tr>
</table>
</div>
</div>
&#13;