sindresorhus/eslint-plugin-unicorn

Rule proposal: prefer-modern-dom-apis - .replaceChildren()

Closed

#2,053 opened on Mar 21, 2023

 (1 comment) (3 reactions) (0 assignees)JavaScript (468 forks)user submission
help wantednew rule

Repository metrics

Stars
 (5,022 stars)
PR merge metrics
 (Avg merge 1d 16h) (399 merged PRs in 30d)

Description

Description

Instead of iterating all children in a DOM Node, we can use a zero-argument replaceChildren() call.

Fail

while (node.lastChild) {
  node.lastChild.remove();
}
while (node.firstChild) {
  node.firstChild.remove();
}

Pass

node.replaceChildren();
node.replaceChildren();

Additional Info

Not the same if iterating node.firstChildElement.remove() or iterating node.lastChildElement.remove() because the DOM structure can look like this:

<div>
  Text Block 1
  <input />
  Text Block 2
</div>

Contributor guide