我是 js 的新手,并試圖在某個 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') 是一個陣列字串而不是一個節點,但我完全不知道節點是什么,也不知道如何更改我的代碼以使其作業。
我真的很感激任何幫助!謝謝。
uj5u.com熱心網友回復:
你可以試試這個:
const top = document.getElementById('top');
Array.from(document.getElementsByClassName('bottom')).forEach(bottom => top.appendChild(bottom))
uj5u.com熱心網友回復:
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>
uj5u.com熱心網友回復:
const top = document.getElementById('top');
var elements = document.getElementsByClassName("myclass");
[].forEach.call(elements, function(el) {
el.appendChild(bottom);
});
您也可以使用此語法,但它與 IE 等較舊的瀏覽器不兼容:
document.querySelectorAll('.myclass').forEach(...)
uj5u.com熱心網友回復:
var html = '';
var elems = document.getElementsByClassName('bottom');
for (let i = 0; i < elems.length; i ) {
html = elems[i].outerHTML;
}
document.getElementById('top').innerHTML = html;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440081.html
標籤:javascript html 节点.js 班级 节点
