title: First getElementsByTagName() returns all elements in HTML (Strange behaviour)
body: <p>I am using PHP to parse HTML provided to me by Wordpress.</p>
  
  <p>This is a post's PHP returned my Wordpress:</p>
  
  <pre><code>&lt;p&gt;Test&lt;/p&gt; 
  &lt;p&gt;
      &lt;img class="alignnone size-thumbnail wp-image-39" src="img.png"/&gt;
  &lt;/p&gt; 
  &lt;p&gt;Ok.&lt;/p&gt;
  </code></pre>
  
  <p>This is my parsing function (with debugging left in):</p>
  
  <pre><code>function get_parsed_blog_post()
  {
      $html = ob_wp_content(false);
  
      print_r(htmlspecialchars($html));
      echo '&lt;hr/&gt;&lt;hr/&gt;&lt;hr/&gt;';
  
      $parse = new DOMDocument();
      $parse-&gt;loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  
      $xpath = new DOMXpath($parse);
      $ps = $xpath-&gt;query('//p');
  
      foreach ($ps as $p) 
      {
          $imgs = $p-&gt;getElementsByTagName('img');
  
          print($imgs-&gt;length);
          echo '&lt;br/&gt;';
  
          if ($imgs-&gt;length &gt; 0)
          {
              $p-&gt;setAttribute('class', 'image-content');
  
              foreach ($imgs as $img)
              {
                  $img-&gt;removeAttribute('class');
              }
          }        
      }
  
      $htmlFinal = $parse-&gt;saveHTML();
  
      print_r(htmlspecialchars($htmlFinal));
      echo '&lt;hr/&gt;&lt;hr/&gt;&lt;hr/&gt;';
  
      return $htmlFinal;
  }
  </code></pre>
  
  <p>The purpose of this code is to remove the classes Wordpress adds to the <code>&lt;img&gt;</code>s, and to set any <code>&lt;p&gt;</code> that contains an image to be a class of <code>image-content</code>.</p>
  
  <p>And this returns:</p>
  
  <pre><code>1
  1
  0
  &lt;p class="image-content"&gt;Test
  &lt;p class="image-content"&gt;
      &lt;img src="img.png"&gt;
  &lt;/p&gt;
  &lt;p&gt;Ok.&lt;/p&gt;&lt;/p&gt;
  </code></pre>
  
  <p>Somehow, it has wrapped the first occurrence of <code>&lt;p&gt;</code> around my entire parsed post, causing the first <code>&lt;p&gt;</code> to have the <code>image-content</code> class incorrectly applied. Why is this happening? How do I stop it?</p>