xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Web API appendChild bugs All In One

Web API appendChild bugs All In One

appendChild replace self element bug

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

document.createElement 创建的 DOM 只能使用一次 bug

error ❌

let ul = document.createElement("ul");
let li = document.createElement("li");
for (i = 0; i <=3; i++) {
  ul.appendChild(li);
}
//

solutions ✅

const ul = document.createElement("ul");
// li = document.createElement("li");

for (i = 0; i < 3; i++) {
   const li = document.createElement("li");
   // console.log('i =', i, ul);
   ul.insertAdjacentElement('beforeend', li);
}
ul;

ul = document.createElement("ul");
li = '';

for (i = 0; i < 3; i++) {
   // 字符串拼接 🚀
   li += '<li></li>';
}

ul.insertAdjacentHTML('beforeend', li);

image

insertAdjacentElement

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement

Zero Width Space / 零宽字符

const ul = document.createElement("ul");
let li = '';

for (i = 0; i < 3; i++) {
   li += '<li>​</li>';
}

ul.insertAdjacentHTML('beforeend', li);

ul;
// <ul>​<li>​&ZeroWidthSpace;​</li>​<li>​&ZeroWidthSpace;​</li>​<li>​&ZeroWidthSpace;​</li>​</ul>​

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

demos

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs

https://stackoverflow.com/questions/69445670/javascript-for-loop-appends-same-element-once

https://stackoverflow.com/questions/69445670/javascript-for-loop-appends-same-element-once/69492392#69492392

https://stackoverflow.com/review/reopen/30015287



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-10-08 15:32  xgqfrms  阅读(43)  评论(1编辑  收藏  举报