Remove <div> innerHTML with php

I try to change a html page through php. The idea is to reinvent the "contenteditable" attribute and change text on the fly. But I want to save it in the original html. For this I have some initial text in a div element. This I convert to a form with a textarea, reload the page and then I can play with the text. Next I want to return the content of the textarea into the original div. It should replace the old text. It seems to work, except that the old text is always appended and I cannot get rid of it. The problem is probably in the setInnerHTML function. I tried:

$element->parentNode->removeChild($element);

but it did not work for some reason. Thanks!

<?php
$text = $_POST["text"];
$id = $_GET["id"];
$ref = $_GET["ref"];
$html = new DOMDocument(); 
$html->loadHTMLFile($ref.".html"); 
$html->preserveWhiteSpace = false;
$html->formatOutput       = true;
$elem = $html->getElementById($id); 

function setInnerHTML($DOM, $element, $innerHTML) 
  {
  $DOM->deleteTextNode($innerHTML);  
  $element->parentNode->removeChild($element);
  $node = $DOM->createTextNode($innerHTML);  
  $element->appendChild($node);
  }
setInnerHTML($html, $elem, $text);


$html->saveHTMLFile($ref.".html");
?>

Upvotes: 0

Views: 521

Answers (1)

pzmarzly
pzmarzly

Reputation: 826

Try changing your setInnerHTML to look like this:

function setInnerHTML($DOM, $element, $innerHTML) {
  $node = $DOM->createTextNode($innerHTML);
  $children = $element->childNodes;
  foreach ($children as $child) {
    $element->removeChild($child);
  }
  $element->appendChild($node);
}

Tell me if it is the result you desired.

Upvotes: 1

Related Questions