Insert created element at start of html tag using PHP DOM
Asked Answered
V

1

6

I'm trying to insert an HTML <base> tag immediately after the opening <head> tag of a page using dom. I've tried using appendChild which just inserts it before the </head> which is no good.

Code im using:

$head = $dom->getElementsByTagName('head')->item(0);
$base = $dom->createElement('base');
$base->setAttribute('href', $url);
$head->parentNode->insertBefore($base, $head);

This inserts the <base> tag before the <head>, which is still no good!

Any ideas? Beer for the correct answer!

Verdi answered 5/7, 2010 at 14:6 Comment(1)
parentNode is necessary? i assume heads' parentnode is html.Relinquish
C
14
$head = $dom->getElementsByTagName('head')->item(0);
$base = $dom->createElement('base');
$base->setAttribute('href',$url);

if ($head->hasChildNodes()) {
    $head->insertBefore($base,$head->firstChild);
} else {
    $head->appendChild($base);
}

If the <head> element already has children, it inserts the <base> element before <head>'s first child. If <head> has no children, it just appends it to <head>.

Caseate answered 5/7, 2010 at 14:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.