You are here

protected function DomHelperTrait::changeNodeName in Embed 8

Rename a DOMNode tag.

Parameters

\DOMNode $node: A DOMElement object.

string $name: The new tag name.

1 call to DomHelperTrait::changeNodeName()
DomHelperTraitTest::testChangeNodeName in tests/src/Unit/DomHelperTraitTest.php
Tests DomHelperTrait::changeNodeName().

File

src/DomHelperTrait.php, line 25

Class

DomHelperTrait
Wrapper methods for manipulating DOM entries.

Namespace

Drupal\embed

Code

protected function changeNodeName(\DOMNode &$node, $name = 'div') {
  if ($node->nodeName != $name) {

    /** @var \DOMElement $replacement_node */
    $replacement_node = $node->ownerDocument
      ->createElement($name);

    // Copy all children of the original node to the new node.
    if ($node->childNodes->length) {
      foreach ($node->childNodes as $child) {
        $child = $replacement_node->ownerDocument
          ->importNode($child, TRUE);
        $replacement_node
          ->appendChild($child);
      }
    }

    // Copy all attributes of the original node to the new node.
    if ($node->attributes->length) {
      foreach ($node->attributes as $attribute) {
        $replacement_node
          ->setAttribute($attribute->nodeName, $attribute->nodeValue);
      }
    }
    $node->parentNode
      ->replaceChild($replacement_node, $node);
    $node = $replacement_node;
  }
}