DiDom\Document::first PHP Method

first() public method

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 ) : Element | DOMElement | null
$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 Element | DOMElement | null
    public function first($expression, $type = Query::TYPE_CSS, $wrapElement = true)
    {
        $nodes = $this->find($expression, $type, false);
        if (count($nodes) === 0) {
            return null;
        }
        return $wrapElement ? $this->wrapNode($nodes[0]) : $nodes[0];
    }

Usage Example

Example #1
0
 /**
  * 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;
 }
All Usage Examples Of DiDom\Document::first