In old school JavaScript, you could do this:
document.body.innerHTML = '<p id="foo">Some HTML</p>' + document.body.innerHTML;
In response to your comment:
[...] I was interested in declaring the source of a new element's attributes and events, not the innerHTML
of an element.
You need to inject the new HTML into the DOM, though; that's why innerHTML
is used in the old school JavaScript example. The innerHTML
of the BODY
element is prepended with the new HTML. We're not really touching the existing HTML inside the BODY
.
I'll rewrite the abovementioned example to clarify this:
var newElement = '<p id="foo">This is some dynamically added HTML. Yay!</p>';
var bodyElement = document.body;
bodyElement.innerHTML = newElement + bodyElement.innerHTML;
// note that += cannot be used here; this would result in 'NaN'
Using a JavaScript framework would make this code much less verbose and improve readability. For example, jQuery allows you to do the following:
$('body').prepend('<p id="foo">Some HTML</p>');