Skip to content

Commit

Permalink
Added support for setting innerHTML and outerHTML of HTML elements.
Browse files Browse the repository at this point in the history
  • Loading branch information
ivopetkov committed Aug 29, 2016
1 parent 06bb7c3 commit a1d5d99
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/HTML5DOMElement.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,29 @@ public function __get($name)
}
}

public function __set($name, $value)
{
if ($name === 'innerHTML') {
while ($this->hasChildNodes()) {
$this->removeChild($this->firstChild);
}
$tmpDoc = new \IvoPetkov\HTML5DOMDocument();
$tmpDoc->loadHTML('<body>' . $value . '</body>');
foreach ($tmpDoc->getElementsByTagName('body')->item(0)->childNodes as $node) {
$node = $this->ownerDocument->importNode($node, true);
$this->appendChild($node);
}
} elseif ($name === 'outerHTML') {
$tmpDoc = new \IvoPetkov\HTML5DOMDocument();
$tmpDoc->loadHTML('<body>' . $value . '</body>');
foreach ($tmpDoc->getElementsByTagName('body')->item(0)->childNodes as $node) {
$node = $this->ownerDocument->importNode($node, true);
$this->parentNode->insertBefore($node, $this);
}
$this->parentNode->removeChild($this);
}
}

private function updateResult($value)
{
$matches = [];
Expand Down
24 changes: 24 additions & 0 deletions tests/Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,18 @@ public function testInnerHTML()
. '</body></html>');

$this->assertTrue($dom->querySelector('body')->innerHTML === '<div>text1</div>');

$dom = new HTML5DOMDocument();
$dom->loadHTML('<div>text1</div>');
$element = $dom->querySelector('div');
$element->innerHTML = 'text2';
$this->assertTrue('<!DOCTYPE html><html><body><div>text2</div></body></html>' === $dom->saveHTML());

$dom = new HTML5DOMDocument();
$dom->loadHTML('<div>text1</div>');
$element = $dom->querySelector('div');
$element->innerHTML = '<div>text1<div>text2</div></div>';
$this->assertTrue('<!DOCTYPE html><html><body><div><div>text1<div>text2</div></div></div></body></html>' === $dom->saveHTML());
}

/**
Expand All @@ -297,6 +309,18 @@ public function testOuterHTML()

$this->assertTrue($dom->querySelector('div')->outerHTML === '<div>text1</div>');
$this->assertTrue((string) $dom->querySelector('div') === '<div>text1</div>');

$dom = new HTML5DOMDocument();
$dom->loadHTML('<div>text1</div>');
$element = $dom->querySelector('div');
$element->outerHTML = 'text2';
$this->assertTrue('<!DOCTYPE html><html><body>text2</body></html>' === $dom->saveHTML());

$dom = new HTML5DOMDocument();
$dom->loadHTML('<div>text1</div>');
$element = $dom->querySelector('div');
$element->outerHTML = '<div>text2<div>text3</div></div>';
$this->assertTrue('<!DOCTYPE html><html><body><div>text2<div>text3</div></div></body></html>' === $dom->saveHTML());
}

/**
Expand Down

0 comments on commit a1d5d99

Please sign in to comment.