Instead of tediously search for workarounds for each type of attribute and event when using the following syntax:
elem = document.createElement("div");
elem.id = 'myID';
elem.innerHTML = ' my Text '
document.body.insertBefore(elem,document.body.childNodes[0]);
Is there a way where I can just declare the entire HTML element as a string? like:
elem = document.createElement("<div id='myID'> my Text </div>");
document.body.insertBefore(elem,document.body.childNodes[0]);
In old school JavaScript, you could do this:
In response to your comment:
You need to inject the new HTML into the DOM, though; that's why
innerHTML
is used in the old school JavaScript example. TheinnerHTML
of theBODY
element is prepended with the new HTML. We're not really touching the existing HTML inside theBODY
.I'll rewrite the abovementioned example to clarify this:
Using a JavaScript framework would make this code much less verbose and improve readability. For example, jQuery allows you to do the following:
Have a look at insertAdjacentHTML
position is the position relative to the element you are inserting adjacent to:
'beforebegin' Before the element itself
'afterbegin' Just inside the element, before its first child
'beforeend' Just inside the element, after its last child
'afterend' After the element itself
As others said the convenient jQuery prepend functionality can be emulated:
While some say it is better not to "mess" with innerHTML, it is reliable in many use cases, if you know this:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
Or:
insertAdjacentHTML
is probably a good alternative: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTMLIf you want to insert HTML code inside existing page's tag use Jnerator. This tool was created specially for this goal.
Instead of writing next code
You can write more understandable structure
To my knowledge, which, to be fair, is fairly new and limited, the only potential issue with this technique is the fact that you are prevented from dynamically creating some table elements.
I use a form to templating by adding "template" elements to a hidden DIV and then using cloneNode(true) to create a clone and appending it as required. Bear in ind that you do need to ensure you re-assign id's as required to prevent duplication.
Instead of directly messing with
innerHTML
it might be better to create a fragment and then insert that:Benefits:
Even though
innerHTML
is used within the function, it's all happening outside of the DOM so it's much faster than you'd think...