Searches for an node in the DOM tree and returns first element or null.
public first ( string $expression, string $type = Query::TYPE_CSS, boolean $wrapElement = true ) : |
||
$expression | string | XPath expression or a CSS selector |
$type | string | The type of the expression |
$wrapElement | boolean | Returns \DiDom\Element if true, otherwise \DOMElement |
return |
/** * Sets inner HTML. * * @param string $html * * @return Element */ public function setInnerHtml($html) { if (!is_string($html)) { throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be string, %s given', __METHOD__, is_object($html) ? get_class($html) : gettype($html))); } // remove all child nodes foreach ($this->node->childNodes as $node) { $this->node->removeChild($node); } if ($html !== '') { Errors::disable(); $html = "<htmlfragment>{$html}</htmlfragment>"; $document = new Document($html); $fragment = $document->first('htmlfragment')->getNode(); foreach ($fragment->childNodes as $node) { $newNode = $this->node->ownerDocument->importNode($node, true); $this->node->appendChild($newNode); } Errors::restore(); } return $this; }
public function testReplaceToNewElement() { $html = '<ul><li>One</li><li>Two</li><li>Three</li></ul>'; $document = new Document($html, false); $first = $document->find('li')[0]; $newElement = new Element('li', 'Foo'); $this->assertEquals($first->getNode(), $first->replace($newElement)->getNode()); $this->assertEquals('Foo', $document->find('li')[0]->text()); $this->assertCount(3, $document->find('li')); // replace with new node $html = '<span>Foo <a href="#">Bar</a> Baz</span>'; $document = new Document($html, false); $anchor = $document->first('a'); $textNode = new \DOMText($anchor->text()); $anchor->replace($textNode); }
public function testFirst() { $html = '<ul><li>One</li><li>Two</li><li>Three</li></ul>'; $document = new Document($html, false); $items = $document->find('ul > li'); $this->assertEquals($items[0]->getNode(), $document->first('ul > li')->getNode()); $this->assertEquals('One', $document->first('ul > li::text')); $document = new Document(); $this->assertNull($document->first('ul > li')); }