简体   繁体   English

将 DOM 元素的第一个子元素移动到最后一个 position 而不创建垃圾节点

[英]Move first child of a DOM element to last position without creating garbage nodes

I want to put the first span element at the bottom so that is goes from this...我想把第一个跨度元素放在底部,这样就可以了……

<div id="items">
<span>1</span>
<span>2</span>
<span>3</span>
</div>

...to this: ...对此:

<div id="items">
<span>2</span>
<span>3</span>
<span>1</span>
</div>

I've tried using the method below to achieve this, but it seems like it creates garbage DOM nodes in the process when looking at the performance monitor in Chrome DevTools.我已经尝试使用下面的方法来实现这一点,但在 Chrome DevTools 中查看性能监视器时,它似乎在进程中创建了垃圾 DOM 节点。

const itemsEl = document.getElementById('items');
itemsEl.append(itemsEl.children[0]);

Is it possible to do this without creating garbage DOM nodes?是否可以在不创建垃圾 DOM 节点的情况下做到这一点?

Try appendChild尝试appendChild

You might try appendChild instead of append , since the former hasa narrower job (only accepts one child, child must be a Node), and so DOM impls might do less stage-setting interally to make it work.您可以尝试appendChild而不是append ,因为前者的工作范围较窄(只接受一个孩子,孩子必须是节点),因此 DOM impls 可能会减少内部设置以使其工作。 The spec is just one step.规范只是一步。

That said, I think you should consider that this "garbage node" situation is specific to Chrome, and not something you can or should plan around.也就是说,我认为您应该考虑这种“垃圾节点”情况是 Chrome 特有的,而不是您可以或应该计划的事情。 Today, WebKit creates a garbage node.今天,WebKit 创建了一个垃圾节点。 Next year it might not.明年可能不会。 The spec for append is just two steps, after all.毕竟, append的规格只有两个步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM