Move all elements with class inside div

I’m brand new to js, and tried to move every elements with certain class inside a certain div.
I made some research and saw a solution that works with id, but when I tried to change it to classNames it didn’t work anymore.
Is there anything more to write ?

Here is my HTML

<div class="bottom">bottom 1</div>
<div class="bottom">bottom 2</div>
<div id="top">top</div>

and my script so far


I understood that appendChild didn’t work because document.getElementsByClassName(‘bottom’) is an array string instead of a node, but I have absolutely no idea what a node is, neither how to change my code for it to work.

I would really appreciate any help at all !


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can try this:

const top = document.getElementById('top');
Array.from(document.getElementsByClassName('bottom')).forEach(bottom => top.appendChild(bottom))

Method 2

const t = document.getElementById('top');
[...document.getElementsByClassName('bottom')].map(el => t.appendChild(el));
<div class="bottom">bottom 1</div>
<div class="bottom">bottom 2</div>
<div id="top">top</div>

Method 3

const top = document.getElementById('top');
var elements = document.getElementsByClassName("myclass");

[], function(el) {

u can also use this syntax but its not compatible with older browsers like IE:


Method 4

var html = '';
var elems = document.getElementsByClassName('bottom');
for (let i = 0; i < elems.length; i++) {
    html += elems[i].outerHTML;
document.getElementById('top').innerHTML = html;

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x