I am trying to insert nodes in my html string. My goal is to insert an element before each h2 tag.
For that, I am using:
$htmlString = "<h2>some html</h2>";
$DOM = new DOMDocument();
$DOM->loadHTML($htmlString);
$itemTitles = $DOM->getElementsByTagName('h2');
for($i = 0; $i < $itemTitles->length; $i ++)
{
$helpNavigatorContents[] = $itemTitles->item($i)->nodeValue;
$textBefore = new DOMNode(
'<a name="'.$itemTitles->item($i)->nodeValue.'"></a>'
);
$itemTitles->item($i)->parentNode->insertBefore(
$textBefore,
$itemTitles->item($i)
);
}
$htmlString = $DOM->saveHTML($DOM);
And here I have a problem with the $textBefore
. When I declare the $textBefore
as a DOMText
, I can insert the text before the node but when I try this with DOMNode
, then I am getting the following error (Demo):
Warning: DOMNode::insertBefore(): Couldn't fetch DOMNode