How to use DOMDocument to add script to HTML5


a) Am I right in assuming the correct format for script in head in HTML5 is <script src="script.js"></script>?

b) How do I achieve the correct result using the DOMDocument?

$domImplementation = new \DOMImplementation ();     

$docType = $domImplementation->createDocumentType ( 'html', '', '' );       

$document = $domImplementation->createDocument ( '', 'html', $docType );

$head = $document->createElement ( 'head' );

$script = $document->createElement ( 'script', '' );

$script->setAttribute ('src', 'script.js');

$head->appendChild ( $script );


<!DOCTYPE html>

<html xmlns="">


    <script src="script.js"/>

The HTML5 validator says

Self-closing syntax (/>) used on a non-void HTML element. Ignoring the slash and treating as a start tag.


Javascript tags, even if they’re loading an external file via the src= attribute, can’t be self closing. You may need to add some non-empty content to the DOM element you’re creating to force it to be non-self closing. A textnode with a single space would do.

Answered By – Marc B

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published