You are here

protected function DomHelperTrait::replaceNodeContent in Embed 8

Replace the contents of a DOMNode.

Parameters

\DOMNode $node: A DOMNode object.

string $content: The text or HTML that will replace the contents of $node.

1 call to DomHelperTrait::replaceNodeContent()
DomHelperTraitTest::testReplaceNodeContent in tests/src/Unit/DomHelperTraitTest.php
Test DomHelperTrait::replaceNodeContent().

File

src/DomHelperTrait.php, line 84

Class

DomHelperTrait
Wrapper methods for manipulating DOM entries.

Namespace

Drupal\embed

Code

protected function replaceNodeContent(\DOMNode &$node, $content) {
  if (strlen($content)) {

    // Load the content into a new DOMDocument and retrieve the DOM nodes.
    $replacement_nodes = Html::load($content)
      ->getElementsByTagName('body')
      ->item(0)->childNodes;
  }
  else {
    $replacement_nodes = [
      $node->ownerDocument
        ->createTextNode(''),
    ];
  }
  foreach ($replacement_nodes as $replacement_node) {

    // Import the replacement node from the new DOMDocument into the original
    // one, importing also the child nodes of the replacement node.
    $replacement_node = $node->ownerDocument
      ->importNode($replacement_node, TRUE);
    $node->parentNode
      ->insertBefore($replacement_node, $node);
  }
  $node->parentNode
    ->removeChild($node);
}