Javascript querySelectorAll 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36318471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:54:55  来源:igfitidea点击:

querySelectorAll is not a function

javascripthtml

提问by ChickenLeg

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. Why I do get that error?

我试图在 var articleFirst 中找到所有的oferts,但是控制台中的返回消息说“querySelectorAll”不是一个函数。为什么我会收到那个错误?

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 不是函数

采纳答案by Valter Júnior

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");

回答by Quentin

querySelectorAllis 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 querySelectorAllwhich returns a Node List (which is an array like object). You would need to loop over the Node List and call querySelectorall on each node in it in turn.

您试图在querySelectorAll返回节点列表(它是一个类似对象的数组)的调用的返回值上调用它。您需要遍历节点列表并querySelector依次调用其中的每个节点上的 all 。

Alternatively, just use a descendant combinator in your initial call to it.

或者,只需在对它的初始调用中使用后代组合器。

var oferts = document.querySelectorAll("article.first .oferts");

回答by Hitmands

You need to use document.querySelectorinstead of document.querySelectorAllbecause the next query depends on a single HTMLElementbut document.querySelectorAllreturns a NodeList.

您需要使用document.querySelector而不是document.querySelectorAll因为下一个查询取决于 asingle HTMLElementdocument.querySelectorAll返回 a 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>