移动所有 class 到 div 的元素
Move all elements with class inside div
我是 js 的新手,并尝试将具有某些 class 的每个元素移动到某个 div 中。
我进行了一些研究,发现了一个适用于 id 的解决方案,但是当我尝试将其更改为 classNames 时,它不再起作用了。
还有什么要写的吗?
这是我的HTML
<div class="bottom">bottom 1</div>
<div class="bottom">bottom 2</div>
<div id="top">top</div>
到目前为止我的脚本
document.getElementById('top').appendChild(document.getElementsByClassName('bottom'))
console.log(document.getElementById('top').innerHTML)
我知道 appendChild 不起作用,因为 document.getElementsByClassName('bottom') 是数组字符串而不是节点,但我完全不知道节点是什么,也不知道如何更改我的代码让它工作。
如果有任何帮助,我将不胜感激!
谢谢
你可以试试这个:
const top = document.getElementById('top');
Array.from(document.getElementsByClassName('bottom')).forEach(bottom => top.appendChild(bottom))
const top = document.getElementById('top');
var elements = document.getElementsByClassName("myclass");
[].forEach.call(elements, function(el) {
el.appendChild(bottom);
});
您也可以使用此语法,但它与 IE 等旧版浏览器不兼容:
document.querySelectorAll('.myclass').forEach(...)
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>
var html = '';
var elems = document.getElementsByClassName('bottom');
for (let i = 0; i < elems.length; i++) {
html += elems[i].outerHTML;
}
document.getElementById('top').innerHTML = html;
我是 js 的新手,并尝试将具有某些 class 的每个元素移动到某个 div 中。 我进行了一些研究,发现了一个适用于 id 的解决方案,但是当我尝试将其更改为 classNames 时,它不再起作用了。 还有什么要写的吗?
这是我的HTML
<div class="bottom">bottom 1</div>
<div class="bottom">bottom 2</div>
<div id="top">top</div>
到目前为止我的脚本
document.getElementById('top').appendChild(document.getElementsByClassName('bottom'))
console.log(document.getElementById('top').innerHTML)
我知道 appendChild 不起作用,因为 document.getElementsByClassName('bottom') 是数组字符串而不是节点,但我完全不知道节点是什么,也不知道如何更改我的代码让它工作。
如果有任何帮助,我将不胜感激! 谢谢
你可以试试这个:
const top = document.getElementById('top');
Array.from(document.getElementsByClassName('bottom')).forEach(bottom => top.appendChild(bottom))
const top = document.getElementById('top');
var elements = document.getElementsByClassName("myclass");
[].forEach.call(elements, function(el) {
el.appendChild(bottom);
});
您也可以使用此语法,但它与 IE 等旧版浏览器不兼容:
document.querySelectorAll('.myclass').forEach(...)
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>
var html = '';
var elems = document.getElementsByClassName('bottom');
for (let i = 0; i < elems.length; i++) {
html += elems[i].outerHTML;
}
document.getElementById('top').innerHTML = html;