gpt4 book ai didi

javascript - 编写此 DOM 操作的更有效/适当的方法?

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:41 24 4
gpt4 key购买 nike

我是 Vanilla JavaScript 的初学者,刚刚编写代码来更改下面的 HTML。它有效,但我想知道是否有更有效/更合适的方法来做到这一点。预先感谢您的帮助。

HTML 之前

<section id="anchor-a">
<p>lorem ipsum....</p>
</section>
<section id="anchor-b">
<p>lorem ipsum....</p>
</section>

HTML 之后

<section>
<div id="anchor-a" class="anchor"></div>
<p>lorem ipsum....</p>
</section>
<section>
<div id="anchor-b" class="anchor"></div>
<p>lorem ipsum....</p>
</section>

我的 JavaScript 代码

const anchor = document.querySelectorAll('[id^="anchor-"]');
anchor.forEach((element) => {
let newDiv = document.createElement('div');
newDiv.classList.add('anchor');
newDiv.setAttribute('id', element.getAttribute("id"));
;
element.insertBefore(newDiv, element.firstChild);
element.removeAttribute('id');
});

最佳答案

一个更简洁的版本是 insertAdjacentHTML,这可能更容易阅读:

const anchor = document.querySelectorAll('[id^="anchor-"]');
anchor.forEach((section) => {
section.insertAdjacentHTML('afterbegin', `<div id="${section.id}">`);
section.removeAttribute('id');
});
// next line is not needed, just cleans up the console output for demonstration
document.currentScript.remove();
console.log(document.body.innerHTML);
<section id="anchor-a">
<p>lorem ipsum....</p>
</section>
<section id="anchor-b">
<p>lorem ipsum....</p>
</section>

还要注意 querySelectorAll 返回一个 NodeList,只有较新的浏览器才有 NodeList.prototype.forEach 函数。对于旧版浏览器和 IE,要么包含一个 polyfill,要么使用 Array.prototype.forEach.call 代替:

Array.prototype.forEach.call(
document.querySelectorAll('[id^="anchor-"]'),
(section) => {
section.insertAdjacentHTML('afterbegin', `<div id="${section.id}">`);
section.removeAttribute('id');
}
);
// next line is not needed, just cleans up the console output for demonstration
document.currentScript.remove();
console.log(document.body.innerHTML);
<section id="anchor-a">
<p>lorem ipsum....</p>
</section>
<section id="anchor-b">
<p>lorem ipsum....</p>
</section>

(当然,如果你想支持 古老的 浏览器,如果使用 ES6+ 语法,请记住除了 polyfill 之外还要转译到 ES5)

关于javascript - 编写此 DOM 操作的更有效/适当的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55701938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com