dom_dom0900_007

Todoリストで並び替えボタンを押すと、Array.from(ul.children)で配列化し、sort後に( A )で一括挿入すると再描画を最小化できる。また、個々のliを直接大量移動するより、先に( B )を使ってバッファ上で並べると効率がよい。

解答

A: append
B: DocumentFragment

解説

DocumentFragmentに並べ替え後の要素を移してから親にappendで挿し替えると、DOMツリーの再計算回数が減りパフォーマンスが向上する。

使用例(サンプルコード)

[ html ]

<ul id="todo"><li>b</li><li>a</li><li>c</li></ul>
<button id="sort">Sort</button>
<script>
sort.onclick = () => {
  const ul = document.getElementById('todo');
  const frag = document.createDocumentFragment(); // (B)
  const items = Array.from(ul.children).sort((a,b)=>a.textContent.localeCompare(b.textContent));
  items.forEach(li => frag.append(li));
  ul.innerHTML = '';
  ul.append(frag); // (A)
};
</script>