You need to use insertBefore
on $tag->parentNode
. You also have to create a new element for every insert (or it'll move the old element).
<?php
$text = 'Some text<h2>More text</h2><h2>Another h2</h2>';
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($text);
$dom->preserveWhiteSpace = false;
foreach ($dom->getElementsByTagName('h2') as $tag) {
$el = $dom->createElement('a');
$el->setAttribute('class', 'foo');
$el->setAttribute('href', '#');
$tag->parentNode->insertBefore($el, $tag);
}
foreach ($dom->getElementsByTagName('h3') as $tag) {
$el = $dom->createElement('a');
$el->setAttribute('class', 'foo');
$el->setAttribute('href', '#');
$tag->parentNode->insertBefore($el, $tag);
}
var_dump($dom->saveHTML());
Output:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>Some text</p>
<a class="foo" href="#"></a>
<h2>More text</h2>
<a class="foo" href="#"></a>
<h2>Another h2</h2>
</body>
</html>