DiDom\Element::replace PHP Method

replace() public method

Replaces a child.
public replace ( $newNode, boolean $clone = true ) : Element
$clone boolean Clone the node if true, otherwise move it
return Element The node that has been replaced
    public function replace($newNode, $clone = true)
    {
        if ($this->node->parentNode === null) {
            throw new LogicException('Can not replace element without parent node');
        }
        if ($newNode instanceof self) {
            $newNode = $newNode->getNode();
        }
        if (!$newNode instanceof DOMNode) {
            throw new InvalidArgumentException(sprintf('Argument 1 passed to %s must be an instance of %s or DOMNode, %s given', __METHOD__, __CLASS__, is_object($newNode) ? get_class($newNode) : gettype($newNode)));
        }
        if ($clone) {
            $newNode = $newNode->cloneNode(true);
        }
        if ($newNode->ownerDocument === null or !$this->getDocument()->is($newNode->ownerDocument)) {
            $newNode = $this->node->ownerDocument->importNode($newNode, true);
        }
        $node = $this->node->parentNode->replaceChild($newNode, $this->node);
        return new Element($node);
    }

Usage Example

示例#1
0
 /**
  * @expectedException LogicException
  */
 public function testReplaceElementWithoutParentNode()
 {
     $element = new Element('div', 'Foo');
     $element->replace(new Element('div', 'Bar'));
 }