Skip to content

Commit a00fe02

Browse files
committed
Fix bug in setInnerHtml: can't rewrite existing content
1 parent dc05790 commit a00fe02

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/DiDom/Element.php

+12-2
Original file line numberDiff line numberDiff line change
@@ -464,9 +464,19 @@ public function setInnerHtml($html)
464464
}
465465

466466
// remove all child nodes
467-
foreach ($this->node->childNodes as $node)
467+
468+
// we need to collect child nodes to array
469+
// because removing nodes from the DOMNodeList on iterating is not working
470+
$childNodes = [];
471+
472+
foreach ($this->node->childNodes as $childNode)
473+
{
474+
$childNodes[] = $childNode;
475+
}
476+
477+
foreach ($childNodes as $childNode)
468478
{
469-
$this->node->removeChild($node);
479+
$this->node->removeChild($childNode);
470480
}
471481

472482
if ($html !== '') {

tests/DiDom/ElementTest.php

+7
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,13 @@ public function testSetInnerHtml()
510510
$this->assertEquals($list, $list->setInnerHtml($html));
511511
$this->assertEquals(['One', 'Two', 'Three'], $list->find('li::text'));
512512

513+
// check inner HTML rewrite works
514+
515+
$html = '<li>Foo</li><li>Bar</li><li>Baz</li>';
516+
517+
$this->assertEquals($list, $list->setInnerHtml($html));
518+
$this->assertEquals(['Foo', 'Bar', 'Baz'], $list->find('li::text'));
519+
513520
$html = '<div id="root"></div>';
514521
$innerHtml = ' Plain text <span>Lorem ipsum.</span><span>Lorem ipsum.</span>';
515522

0 commit comments

Comments
 (0)