简体   繁体   中英

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.

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

Is it possible to do this without creating garbage DOM nodes?

Try 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. 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. Today, WebKit creates a garbage node. Next year it might not. The spec for append is just two steps, after all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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