17

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>  
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Teiv
  • 2,605
  • 10
  • 39
  • 48
  • Btw you don't need HTML entities to display HTML in your post. Just intend any code by 4 spaces or just mark your code and click the `{}` button. See my edit as example. – Felix Kling Dec 25 '10 at 11:19

1 Answers1

24

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);
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • In case anyone came here trying to find how to do this with JavaScript, you can just use [prepend](https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/prepend) on the parent node. – Brady Dowling Jul 07 '20 at 19:21