Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This is my 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:

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

Error:

Uncaught TypeError: articleFirst.querySelectorAll is not a function

like image 573
ChickenLeg Avatar asked Mar 30 '16 19:03

ChickenLeg


3 Answers

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

3rd pary edit

To answer

Why I do get that error?

Quentin’s post has the answer

like image 114
Valter Júnior Avatar answered Nov 02 '22 02:11

Valter Júnior


querySelectorAll is a method found on Element and Document nodes in the DOM.

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). You would need to loop over the Node List and call querySelector all on each node in it in turn.

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

var oferts = document.querySelectorAll("article.first .oferts");
like image 13
Quentin Avatar answered Nov 02 '22 01:11

Quentin


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.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>
like image 8
Hitmands Avatar answered Nov 02 '22 01:11

Hitmands