超越 appendChild:HTML 的更便捷方法完成!

2025-06-04

超越 appendChild:更便捷的 HTML 方法

完毕!

我从事 Web 开发已经有一段时间了。时间太长了,以至于当我编写原生 HTML/JS 代码时,我的首要任务就是添加新的 HTML 元素,以及随之而来的.appendChild()一系列大量代码调用。createElement

但实际上,我们现在可以使用一些鲜为人知的便捷方法(好吧,在后 IE11 时代,所有开发人员都应该使用这种方法)。🌎👍 我并不是反对你的框架或组件,但有时候,你只需要编写原生 JS 代码。🍦

单线元素创建

我承认😅这实际上不是一行,而是一条语句

const el = Object.assign(document.createElement('div'), {
  textContent: `Your div now has text`,
  className: 'and-is-classy',
});
Enter fullscreen mode Exit fullscreen mode

该帮助程序Object.assign在 IE11 中不可用。

移除自身

这个相当有名。

const el = document.getElementById('something');
el.remove();   // instead of el.parentNode.removeChild(el)
Enter fullscreen mode Exit fullscreen mode

插入元素文本

.append()方法可以附加任何实际元素,或者如果传递一个字符串,它将自动创建一个文本节点。它接受任意数量的参数。

el.append(document.createElement('hr'), 'I get upgraded to a text node!');
Enter fullscreen mode Exit fullscreen mode

还有.prepend()与相反的操作.append()。它会将所有元素按顺序插入到元素的开头:

const heading = Object.assign(document.createElement('h2', {
  textContent: 'List Of Awesome HTML Methods',
});
list.prepend(heading, `You Won't Believe How Many We Found!`);
Enter fullscreen mode Exit fullscreen mode

相对于元素插入

每个元素都有方法.before().after()。这些方法会在当前节点的相邻位置插入新的 HTML 节点。与上述方法类似,它们可以接受任意数量的其他元素或字符串。

myHeading.before(superHeading);
myHeading.after(`Here's a list of awesome stuff`, theList);
Enter fullscreen mode Exit fullscreen mode

⚠️ 有一点需要注意:在我们的例子中,如果myHeading它实际上不在页面上 - 它是一个临时元素 - 这些方法将会静默失败而不会抛出Error

替换自身

现在,我们不用再跳舞了,而是parentNode.replaceChild可以自毁一个元素,并用新元素替换它。同样,我们可以用任意数量的其他元素或字符串(甚至没有!)替换自己。

const fancyItem = Object.assign(document.createElement('strong'), {
  textContent: 'fancy',
});
someFancyHeading.replaceWith('Less', fancyItem, 'heading');
someFancyHeading.replaceWith();  // although you could just use .remove 🤷
Enter fullscreen mode Exit fullscreen mode

职业力量套装

如果要将类的状态设置为变量 true 或 false,则可以传递第二个参数.classList.toggle

const someState = false;
theDiv.classList.toggle('foo', !someState);  // forces foo on
theDev.classList.toggle('bar', someState);   // forces bar off
// result e.g. <div id="theDiv" class="foo">
Enter fullscreen mode Exit fullscreen mode

可能是众所周知的。但如果你明确表示不支持 IE11,那么现在确信它已经可以正常工作了。🎉

完毕!

我遗漏了什么吗?如果你最近发现了其他可以戒掉的旧习惯,请告诉我。

9👋

文章来源:https://dev.to/chromiumdev/beyond-appendchild-better-convenience-methods-for-html-55n4
PREV
开发者成长的 7 个小技巧
NEXT
为什么新的 Firebase Web v9 模块化 SDK 会改变游戏规则