Search code examples
javascripthtmlnode.jsclassnodes

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

document.getElementById('top').appendChild(document.getElementsByClassName('bottom'))
console.log(document.getElementById('top').innerHTML)

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 ! Thanks.


Solution

  • 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>