0

So I'm trying to select 3 divs in my parent element. With my current code the result is I get 162 nodeLists back, instead of just the 3 main divs in that parent element.

The page code looks like this (simplified):

var parent = document.querySelector('.parent');

var wantedChildren = parent.querySelectorAll('div');

console.log(wantedChildren);
<div class="parent">
  <div class="wantedChild">
    <div class="unwantedChild">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
    <div class="unwantedChild"></div>
  </div>
  <div class="wantedChild">
    <div class="unwantedChild"></div>
    <div class="unwantedChild"></div>
  </div>
  <div class="wantedChild">
    <div class="unwantedChild"></div>
    <div class="unwantedChild"></div>
  </div>
</div>

So the divs are just examples. The entire code on the page is way bigger.

I just want those 3 divs.

Does anybody know how to do this?

isherwood
  • 58,414
  • 16
  • 114
  • 157

2 Answers2

1

You can use direct child selector

const wantedChildren = document.querySelectorAll('.parent > div');

console.log(wantedChildren);
<div class="parent">
  <div class="wantedChild">
    <div class="unwantedChild">
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
    <div class="unwantedChild"></div>
  </div>
  <div class="wantedChild">
    <div class="unwantedChild"></div>
    <div class="unwantedChild"></div>
  </div>
  <div class="wantedChild">
    <div class="unwantedChild"></div>
    <div class="unwantedChild"></div>
  </div>
</div>
Konrad
  • 21,590
  • 4
  • 28
  • 64
1
var wantedChildren = parent.children;

https://developer.mozilla.org/en-US/docs/Web/API/Element/children

isherwood
  • 58,414
  • 16
  • 114
  • 157