Search code examples
javascriptnode.jspuppeteer

How to select all child div with same class using Puppeteer?


I'm new for Puppeteer and I'm trying to get textContent from two divs that using same class.

<div class="post-item">
   <div class="post-item-info">
      <span class="post-item-status post-comment"></span>
      3
   </div>
   <div class="post-item-info">
      <span class="post-item-status post-vote"></span>
      5
   </div>
</div>

The result that I'm expecting is return an array [3,5]. My current code is below.

let postInfo = element.querySelector('.post-item-info');

The problem is it is only return the first one. Please let me know how to do it.


Solution

  • Your selector should be like const nodes = element.querySelectorAll('.post-item-info');. Then to access individual items in the returned collection, use a traditional for loop like

    for(let i = 0; i < nodes.length; i++){
          const currentNode = nodes[i];
          // doStuffWith(currentNode);
        }