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
The code doesn’t make any sense.
DOMNodedoes not have a constructor. It is not supposed to be created at all. You are supposed to create specific node types throughDOMDocumentto have them associated with the Document.Assuming you want to prepend all the H2 element with an anchor, this is how to do it:
Demo http://codepad.org/N0dPcLwT
To wrap the H2 elements into the A element, simply do the same and add
Demo http://codepad.org/w7Hi0Bmz