title: PHP DOM append HTML in Wordpress filter
body: <p>I created a Wordpress filter using the DOM API method that was suggested here <a href="https://wordpress.stackexchange.com/a/61036/103233">https://wordpress.stackexchange.com/a/61036/103233</a> to change some attributes of my images:</p>
  
  <pre><code>function add_lazyload($content) {
  
      $content = mb_convert_encoding($content, 'HTML-ENTITIES', "UTF-8");
      $dom = new DOMDocument();
      @$dom-&gt;loadHTML($content);
  
      foreach ($dom-&gt;getElementsByTagName('img') as $node) {  
          $oldsrc = $node-&gt;getAttribute('src');
          $node-&gt;setAttribute('data-src', $oldsrc );
          $newsrc = get_template_directory_uri() . '/images/placeholder.gif';
          $node-&gt;setAttribute('src', $newsrc);
      }
  
      $newHtml = preg_replace('/^&lt;!DOCTYPE.+?&gt;/', '', str_replace( array('&lt;html&gt;', '&lt;/html&gt;', '&lt;body&gt;', '&lt;/body&gt;'), array('', '', '', ''), $dom-&gt;saveHTML()));
      return $newHtml;
  }
  add_filter('the_content', 'add_lazyload');
  add_filter('post_thumbnail_html', 'add_lazyload');
  </code></pre>
  
  <p>How can I add a HTML element within the <code>foreach</code> loop? </p>
  
  <p>I tried adding a new <code>DOMDocument</code> and displaying it within the loop:</p>
  
  <pre><code>$test = new DOMDocument();
  $test-&gt;loadHTML('&lt;a&gt;Hello&lt;/a&gt;');
  $test-&gt;saveHTML();
  </code></pre>
  
  <p>But this first prints all new <code>$test</code> elements (one for each loop) and then my altered <code>$newHTML</code> is printed. I want to append the new <code>$test</code> element to each <code>img</code> of the <code>foreach</code> loop. I never used DOM before... any suggestions? <code>appendChild</code>? But how?</p>