Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group and collapse <a> elements by class in javascript

This question made my mind really busy.

I have a set of tags like below

<a class='c1'>1</a>
<a class='c2'>2</a>
<a class='c3'>3</a>
<a class='c1'>4</a>
<a class='c1'>5</a>
<a class='c3'>6</a>
<a class='c2'>7</a>

What I need to do is to start from above and group elements together by class so that I can add a collapse to the elements. so the final results should be like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class='collapse'>
 <a class='c1'>1</a>
 <a class='c1'>4</a>
 <a class='c1'>5</a>
</div>
<div class='collapse'>
 <a class='c2'>2</a>
 <a class='c2'>7</a>
</div>
<div class='collapse'>
 <a class='c3'>3</a>
 <a class='c3'>6</a>
</div>

I have tried JS scripts with tones of variable that is really hacky and does not work. Is there a simple and clean way to do this?

thanks.

>Solution :

You can do it this way

for(let i = 1; i<=3; i++){
    let tags = document.querySelectorAll(`.c${i}`);
    let div = document.createElement('div');
        div.classList = 'collapse';
    tags.forEach(tag =>{
        div.appendChild(tag);
    });
    document.body.appendChild(div);
}
/* CSS just to demonstrate */
.collapse {
  margin-block: 1rem;
  border: blue solid 3px;
  display:flex;
  flex-direction: column;
}
<a class='c1'>1</a>
<a class='c2'>2</a>
<a class='c3'>3</a>
<a class='c1'>4</a>
<a class='c1'>5</a>
<a class='c3'>6</a>
<a class='c2'>7</a>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading