Manu
Manu

Reputation: 81

php dom only edit parent element and not child elements

I am trying to edit nodevalue of only the parent element (eg hold1) and not the child elements. The below code successfully lets me edit the child elements but when i edit the parent element, it removes the child elements completely. Please help.

$file = 'home/aa.php';
$doc = new DOMdocument();
$doc = loadHTMLFile($file);
$element = $doc->getElementById('hold1');
$element->nodeValue= "THIS IS SPARTA";
$myfile = fopen($file,'w+'); // i have tried c, c+, a+, r+ , none helps
$html = fwrite($myfile,$doc->saveHTML());

//aa.php
<div id = "hold1"> 
<div id = "hold2"> Tom is Cruise </div>
<div id = "hold3"> Ben Stiller parody </div>
</div>

Upvotes: 0

Views: 34

Answers (1)

user3942918
user3942918

Reputation: 26385

By setting the nodeValue you're setting the entirely body of the element. You need to be explicit where you want the new text node to be. Example:

$element = $doc->getElementById('hold1');
$element->insertBefore($doc->createTextNode("THIS IS SPARTA"), $element->firstChild);

puts it in at the beginning

<div id="hold1">THIS IS SPARTA
<div id="hold2"> Tom is Cruise </div>
<div id="hold3"> Ben Stiller parody </div>
</div>

Upvotes: 1

Related Questions