Jared
Jared

Reputation: 2096

How to insert elements into new element with DOMDocument

Basically what I am trying to do is create a div with a css class, put some elements inside that, then replace the same HTML with my new div. I've tried many different ways but here's the most recent one, which fails.

$dom = new DOMDocument( '1.0', strtolower( get_bloginfo( 'charset' ) ) );
@$dom->loadHTML( '<div>' . $content . '</div>' );
$dom->formatOutput = true;

foreach( $dom->getElementsByTagName( 'img' ) as $image ) {
    $copy_node = null;

    if( $image->parentNode->tagName == 'a' )
        $copy_node = $image->parentNode;

    if( !is_null( $copy_node ) && $copy_node->parentNode->tagName == 'p' )
        $copy_node = $copy_node->parentNode;

    if( is_null( $copy_node ) )
        $copy_node = $image;

    $wrap = $dom->createElement( 'div' );
    $wrap->setAttribute( 'class', 'some-css-class' );

    // Insert $copy_node into it - doesn't work
    $wrap->appendChild( $copy_node );

    // Replace the node with the new one
    $copy_node->parentNode->replaceChild( $wrap, $copy_node );

}

Could someone explain how to insert some elements into a newly created one so that I can then replace some elements with my new one in the document?

Upvotes: 0

Views: 289

Answers (1)

salathe
salathe

Reputation: 51950

Change the order of operations:

  • replacement first
  • append second

Otherwise, you're trying to replace $wrap's $copy_node child element with $wrap, which makes no sense.

By doing the replacement first, wrapping element is inserted where the to-be-wrapped element was. This leave the to-be-wrapped element part of the document but not in the tree any more. To give it a place in the tree, it is just a matter of appending it to the wrapping element.

Upvotes: 1

Related Questions