Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append and prepend text nodes to a HTML element using DOM?

Here is my HTML code

<html> 
    <body>
        <div>A sample block <div>and child block</div></div>    
    </body>
</html>

How can I use DOM to append and prepend text nodes to the BODY elements without hurting its siblings?

$dom = new DOMdocument();    
@$dom->loadHTML($html);    
$xpath = new DOMXPath($dom);    
$body = $xpath->query('//body')->item(0);    

like this

<html> 
    <body>
        Newly prepended text
        <div>A sample block <div>and child block</div></div>
        Newly appended text    
    </body>
</html>  
like image 464
Teiv Avatar asked Dec 25 '10 11:12

Teiv


1 Answers

You can create text nodes with DOMText (or by using DOMDocument::createTextNode):

$before = new DOMText('Newly prepended text');
// $before = $dom->createTextNode('Newly prepended text');
$after = new DOMText('Newly appended text');
// $after = $dom->createTextNode('Newly appended text');

Now, appending is just:

$body->appendChild($after);

For prepending, we can use DOMNode::firstChild to get the first child of the body and DOMNode::insertBefore:

$body->insertBefore($before, $body->firstChild);
like image 188
Felix Kling Avatar answered Sep 28 '22 07:09

Felix Kling