如何将 DOM 元素设置为第一个子元素?

新手上路,请多包涵

我有一个元素 E,我正在向它附加一些元素。突然间,我发现下一个要追加的元素应该是 E 的第一个孩子。有什么诀窍,怎么做?方法 unshift 不起作用,因为 E 是一个对象,而不是数组。

很长的路要走,遍历 E 的孩子并移动他们的 key++,但我确信有一个更漂亮的方法。

原文由 Popara 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答
var eElement; // some E DOM instance
 var newFirstElement; //element which should be first in E

 eElement.insertBefore(newFirstElement, eElement.firstChild);

原文由 nemisj 发布,翻译遵循 CC BY-SA 2.5 许可协议

2018版 prepend

 parent.prepend(newChild)  // [newChild, child1, child2]

这就是现代 JS!它比以前的选项更具可读性。它目前在 Chrome、FF 和 Opera 中可用。

添加到末尾的等效项是 append ,替换旧的 appendChild

 parent.append(newChild)  // [child1, child2, newChild]

高级用法

  1. 您可以传递多个值(或使用扩展运算符 ... )。
  2. 任何字符串值都将添加为文本元素。

例子:

 parent.prepend(newChild, "foo")   // [newChild, "foo", child1, child2]

const list = ["bar", newChild]
parent.append(...list, "fizz")    // [child1, child2, "bar", newChild, "fizz"]

相关的 DOM 方法

  1. 阅读更多- child.beforechild.after
  2. 阅读更多- child.replaceWith

Mozilla 文档

我可以用吗

原文由 Gibolt 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题