title: Replace Tag in HTML with DOMDocument
body: <p>I'm trying to edit html tags with DOMDocument::loadHTML in php. The html data is a part of html and not the whole page. I followed what this page (<a href="https://stackoverflow.com/questions/4824503/php-domdocument-need-to-change-replace-an-existing-html-tag-w-a-new-one">PHP - DOMDocument - need to change/replace an existing HTML tag w/ a new one</a>) says.</p>
  
  <p>This should convert pre tags into div tags but it gives "Fatal error: Uncaught exception 'DOMException' with message 'Not Found Error'." </p>
  
  <pre><code>&lt;?php
  $contents = &lt;&lt;&lt;STR
  &lt;pre&gt;hi&lt;/pre&gt;
  &lt;pre&gt;hello&lt;/pre&gt;
  &lt;pre&gt;bye&lt;/pre&gt;
  STR;
  
  $dom = new DOMDocument;
  @$dom-&gt;loadHTML($contents);
  
  foreach( $dom-&gt;getElementsByTagName("pre") as $nodePre ) {
      $nodeDiv = $dom-&gt;createElement("div", $nodePre-&gt;nodeValue);
      $dom-&gt;replaceChild($nodeDiv, $nodePre);
  }
  
  echo $dom-&gt;saveHTML();
  ?&gt;
  </code></pre>
  
  <p>[Edit]
  While I'm trying to iterate the node object backwards, I get this error, 'Notice: Trying to get property of non-object...' </p>
  
  <pre><code>&lt;?php
  $contents = &lt;&lt;&lt;STR
  &lt;pre&gt;hi&lt;/pre&gt;
  &lt;pre&gt;hello&lt;/pre&gt;
  &lt;pre&gt;bye&lt;/pre&gt;
  STR;
  
  $dom = new DOMDocument;
  @$dom-&gt;loadHTML($contents);
  $domPre = $dom-&gt;getElementsByTagName('pre');
  $length = $domPre-&gt;length;
  
      For ($i = $length; $i &gt; -1 ; $i--) {
          $nodePre = $domPre-&gt;item($i);
          echo $nodePre-&gt;nodeValue . '&lt;br /&gt;';
  //      $nodeDiv = $dom-&gt;createElement("div", $nodePre-&gt;nodeValue);
  //      $dom-&gt;replaceChild($nodeDiv, $nodePre);
      }
  
      // echo $dom-&gt;saveHTML();
  ?&gt;
  </code></pre>
  
  <p>[Edit]
  Okey, solved. Since the answered code has some error I post the solution here. Thanks all.</p>
  
  <p>Solution: </p>
  
  <pre><code>&lt;?php
  $contents = &lt;&lt;&lt;STR
  &lt;pre&gt;hi&lt;/pre&gt;
  &lt;pre&gt;hello&lt;/pre&gt;
  &lt;pre&gt;bye&lt;/pre&gt;
  STR;
  
  $dom = new DOMDocument;
  @$dom-&gt;loadHTML($contents);
  $domPre = $dom-&gt;getElementsByTagName('pre');
  $length = $domPre-&gt;length;
  
  For ($i = $length - 1; $i &gt; -1 ; $i--) {
      $nodePre = $domPre-&gt;item($i);
      $nodeDiv = $dom-&gt;createElement("div", $nodePre-&gt;nodeValue);
      $nodePre-&gt;parentNode-&gt;replaceChild($nodeDiv, $nodePre);
  }
  
  echo $dom-&gt;saveHTML();
  ?&gt;
  </code></pre>