sindresorhus/eslint-plugin-unicorn

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

Chiusa

#2053 aperta il 21 mar 2023

 (1 commento) (3 reazioni) (0 assegnatari)JavaScript (468 fork)user submission
help wantednew rule

Metriche repository

Star
 (5022 stelle)
Metriche merge PR
 (Merge medio 1g 16h) (399 PR mergiate in 30 g)

Descrizione

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>

Guida contributor