gpt4 book ai didi

javascript - 适用于单个命令但不适用于迭代的命令

转载 作者:太空宇宙 更新时间:2023-11-04 15:40:00 26 4
gpt4 key购买 nike

我尝试从特定 document.querySelectorAll() 的迭代中获取列表。我使用这个迭代:

for (i = 0; i < document.querySelector('li[dat*="era"]').length; ++i) { document.querySelectorAll('li[dat*="era"] ul li.title div')[i].textContent }

它给我返回这个错误:

Uncaught TypeError: Cannot read property 'textContent' of undefined at <anonymous>:2:64

仅当我使用单个值时它才有效

document.querySelectorAll('li[dat*="era"] ul li.title div')[0].textContent

如何才能作为单个命令而不是作为迭代工作?

示例 HTML:

<li id="r01" dat="era">
<ul class="ref">
<li class="sth"> </li>
<li class="title">
<div>
Text 1 for retrieve
</div>
</li>
<ul>
</li>
<li id="r02" dat="era">
<ul class="ref">
<li class="sth"> </li>
<li class="title">
<div>
Text 2 for retrieve
</div>
</li>
<ul>
</li>

最佳答案

尝试以下代码片段

// Your code, doesnt throw error what you have specified. 
// But when document.querySelector returns null(when theres no specified tag, it throws

for (i = 0; i < document.querySelector('li[dat*="era"]').length; ++i) { document.querySelectorAll('li[dat*="era"] ul li.title div')[i].textContent }


// Use document.querySelectorAll(...) once for performance
var l = document.querySelectorAll('li[dat*="era"] ul li.title div')
for (i = 0; i < l.length; ++i) {
console.log(l[i].textContent)
}
<li id="r01" dat="era">
<ul class="ref">
<li class="sth"> sth 1 </li>
<li class="title">
<div>
Text 1 for retrieve
</div>
</li>
</ul>
</li>
<li id="r02" dat="era">
<ul class="ref">
<li class="sth">sth 2</li>
<li class="title">
<div>
Text 2 for retrieve
</div>
</li>
</ul>
</li>

关于javascript - 适用于单个命令但不适用于迭代的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43963727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com