[英]querySelectorAll is not a function
I'm trying to find all oferts in the var articleFirst, but the return message in the console says that "querySelectorAll" is not a function.我试图在 var articleFirst 中找到所有的 ofert,但控制台中的返回消息说“querySelectorAll”不是一个函数。 Why I do get that error?
为什么我会收到那个错误?
This is my HTML:这是我的 HTML:
<article class="first">
<div class="feature parts">
<div class="oferts">
<div class="heart icons"></div>
<h1>Build with passion</h1>
</div>
</div>
</article>
This is my JavaScript:这是我的 JavaScript:
var articleFirst = document.querySelectorAll("article.first");
var oferts = articleFirst.querySelectorAll(".oferts");
Error:错误:
Uncaught TypeError: articleFirst.querySelectorAll is not a function
未捕获的类型错误:articleFirst.querySelectorAll 不是函数
querySelectorAll
is a method found on Element and Document nodes in the DOM. querySelectorAll
是在DOM中的Element和Document节点上找到的方法。
You are trying to call it on the return value of a call to querySelectorAll
which returns a Node List (which is an array like object). 您试图在对
querySelectorAll
的调用的返回值上调用它,该调用返回节点列表(这是一个类似于对象的数组)。 You would need to loop over the Node List and call querySelector
all on each node in it in turn. 您需要循环遍历节点列表并依次在其中的每个节点上调用
querySelector
all。
Alternatively, just use a descendant combinator in your initial call to it. 或者,只需在初始调用时使用后代组合子。
var oferts = document.querySelectorAll("article.first .oferts");
Try do do this: 尝试这样做:
var articleFirst = document.querySelectorAll("article.first");
console.log(articleFirst)
var oferts = articleFirst[0].querySelectorAll(".oferts");
console.log(oferts)
With console you can see what is happening. 使用控制台,您可以看到正在发生的事情。
Or just do this: 或者只是这样做:
document.querySelectorAll("article.first .oferts");
You need to use document.querySelector
instead of document.querySelectorAll
because the next query depends on a single HTMLElement
but document.querySelectorAll
returns a NodeList
. 您需要使用
document.querySelector
而不是document.querySelectorAll
因为下一个查询依赖于single HTMLElement
但document.querySelectorAll
返回NodeList
。
document.addEventListener('DOMContentLoaded', TestCtrl); function TestCtrl() { var firstArticle = document.querySelector('article.first'); console.log('oferts', firstArticle.querySelectorAll('.oferts')); }
<article class="first"> <div class="feature parts"> <div class="oferts"> <div class="heart icons"></div> <h1>Build with passion</h1> </div> </div> </article>
A little verbose but you could try qselectorAll('article') then turn that nodeList into an array and pick the first index.. so something like:有点冗长,但你可以尝试 qselectorAll('article') 然后把那个 nodeList 变成一个数组并选择第一个索引..所以是这样的:
let articleList = querySelectorAll('article'); // makes a NodeList of all article tags on the webpage
let article = Array.from(articleList);
article[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.