Home > Net >  Move all elements with class inside div
Move all elements with class inside div

Time:03-08

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

CodePudding user response:

You can try this:

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

CodePudding user response:

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

CodePudding user response:

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

[].forEach.call(elements, function(el) {
    el.appendChild(bottom);
});

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

document.querySelectorAll('.myclass').forEach(...)

CodePudding user response:

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