0
<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>

<div class="main">
    <p>I don't want this</p>
    <div class="sub">I want this</div>
</div>

<div class="main">
    <p>I don't want this</p>
    <div class="sub second">I don't want this</div>
</div>

Im trying to use QuerySelectorAll to return all "sub" divs nested inside "main" divs. Im currently using

document.querySelectorAll(".main .sub")

but this returns all divs that class name begins with "sub" so it also return divs with the class name "sub second" or "sub third" is it possible to just select divs thats class are "sub".

I also want to click on the results after using

document.querySelectorAll(".main .sub").click()

but this returns an error i think this is becasue

.click()

is only designed to work with one object at a time. Is it possible to select all divs with the class name "sub" and then click on them using something similar to

.click()
A. Seidel
  • 43
  • 1
  • 1
  • 7

2 Answers2

0

Look at the accepted answer here: Fastest way to convert JavaScript NodeList to Array?

Array.prototype.slice.call(document.querySelectorAll(".main .sub")).forEach(function(el){
  el.click();
})

EDIT 1 - Timeout

To timeout between each click, simple add a setTimeout call within a closed scope, reference the iteration and multiply with the desired delay:

Array.prototype.slice.call(document.querySelectorAll(".main .sub")).forEach(function (el, i) {
    (function (a) {
        setTimeout(function () {
            el.click();
        }, (10 * 1000) * a);
    })(i);
})
Community
  • 1
  • 1
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
0

You can use this selector:

document.querySelectorAll(".main [class='sub']")

You can iterate over result items as follows:

var divs = document.querySelectorAll(".main [class='sub']");

[].forEach.call(divs, function(div) {
  // do whatever
  div.style.color = "red";
});
<div class="main">
<p>I don't want this</p>
<div class="sub">I want this</div>
</div>

<div class="main">
    <p>I don't want this</p>
    <div class="sub">I want this</div>
</div>

<div class="main">
    <p>I don't want this</p>
    <div class="sub second">I don't want this</div>
</div>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95