A. Seidel A. Seidel - 5 months ago 14
Javascript Question

QuerySelectorAll returns more than expected

<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()

Answer

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>