Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
Get all elements of class but group by siblings

Is there a simple way to select all elements of a class, but group them by siblings?

For example:

<div class="main-div">
    <div class="get-this"></div>
    <div class="get-this"></div>
    <div class="get-this"></div>
    <div class="sub-div">
        <div class="get-this"></div>
        <div class="get-this"></div>
    </div>
</div>
<div class="get-this"></div>
<div class="get-this"></div>
<div class="get-this"></div>

If I wanted to get all the elements of class get-this but wanted to loop through the elements that are siblings like in main-div, sub-div and outside of any div separately without assigning a separate class? I can't think of a good way to do this without traversing the entire DOM.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Put their parent elements into a Set, then take the children of each parent.

const parents = new Set(
  [...document.querySelectorAll('.get-this')]
    .map(div => div.parentElement)
);
const divs = [...parents].map(
  parent => [...parent.children].filter(child => child.matches('.get-this'))
);
console.log(divs);
<div class="main-div">
    <div class="get-this"></div>
    <div class="get-this"></div>
    <div class="get-this"></div>
    <div class="sub-div">
        <div class="get-this"></div>
        <div class="get-this"></div>
    </div>
</div>
<div class="get-this"></div>
<div class="get-this"></div>
<div class="get-this"></div>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!