Home > Blockchain >  Get all elements of class but group by siblings
Get all elements of class but group by siblings

Time:07-16

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

For example:

<div >
    <div ></div>
    <div ></div>
    <div ></div>
    <div >
        <div ></div>
        <div ></div>
    </div>
</div>
<div ></div>
<div ></div>
<div ></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.

CodePudding user response:

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 >
    <div ></div>
    <div ></div>
    <div ></div>
    <div >
        <div ></div>
        <div ></div>
    </div>
</div>
<div ></div>
<div ></div>
<div ></div>

  • Related