I’m trying to pass a block of HTML through PHP’s DOMDocument to refactor <img> elements inline with: http://www.appelsiini.net/projects/lazyload
For each <img> I’m trying to insert a refactored duplicate, then wrap the original in <noscript> tags for a non-JS fallback.
Example:
Input:
<img src="img/example.jpg" width="640" heigh="480">
Output:
<img class="lazy" src="img/grey.gif" data-original="img/example.jpg" width="640" heigh="480"><noscript><img src="img/example.jpg" width="640" heigh="480"></noscript>
I have the wrapping working and the new element also constructs correctly. The problem is that the second appendChild (below) doesn’t work and I can’t figure out why. Can anyone provide a solution?
I have the following code:
$noScript = $dom->createElement('noscript');
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src = $image->getAttribute('src');
$alt = $image->getAttribute('alt');
$title = $image->getAttribute('title');
$style = $image->getAttribute('style');
$newImage = $dom->createElement('img');
$newImage->setAttribute('class', 'lazy');
$newImage->setAttribute('data-original', $src);
$newImage->setAttribute('src', '/images/whitespace.gif');
if ($style) $newImage->setAttribute('style', $style);
if ($alt) $newImage->setAttribute('alt', $alt);
if ($title) $newImage->setAttribute('title', $title);
$noScriptClone = $noScript->cloneNode();
$image->parentNode->replaceChild($noScriptClone, $image);
$noScriptClone->appendChild($image);
$noScriptClone->parentNode->appendChild($newImage);
}
return $dom->saveHTMLExact();
I did solve this (in a roundabout kind of way) but forgot to post my solution – until now.
I ended up using QueryPath which worked out really well.