I want to get only direct child elements with getElementsByClassName. Now I have e.g. this HTML

<div class="parent">
  <div class="content">
    <div class="content"></div>
  </div>
  <div class="content"></div>
</div>

And I only want the two div which is direct childs to div with "parent" class name.

const parentElement = ...
const contents = parentElement.getElementsByClassName('content');
console.log(contents); // returns three elements

2 Answers

3
CertainPerformance On Best Solutions

You can use querySelectorAll instead, and use the selector string .parent > .content to select .contents which are direct children of .parent:

const contents = document.querySelectorAll('.parent > .content');
console.log(contents.length);
<div class="parent">
  <div class="content">
    <div class="content"></div>
  </div>
  <div class="content"></div>
</div>

If your HTML has more than one parent, and you only want to select the children .content of a single parent, then select that parent, call querySelectorAll on it (instead of the document), and use :scope > .content:

const contents = first.querySelectorAll(':scope > .content');
console.log(contents.length);
<div class="parent" id="first">
  <div class="content">
    <div class="content"></div>
  </div>
  <div class="content"></div>
</div>

<div class="parent">
  <div class="content">
    <div class="content"></div>
  </div>
  <div class="content"></div>
</div>

1
Mamun On

You can use children property

const contents = document.querySelector('.parent').children;
console.log(contents); // returns two elements
<div class="parent">
  <div class="content">
    <div class="content"></div>
  </div>
  <div class="content"></div>
</div>