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]);
Instead of directly messing with innerHTML
it might be better to create a fragment and then insert that:
function create(htmlStr) { var frag = document.createDocumentFragment(), temp = document.createElement('div'); temp.innerHTML = htmlStr; while (temp.firstChild) { frag.appendChild(temp.firstChild); } return frag; } var fragment = create('<div>Hello!</div><p>...</p>'); // You can use native DOM methods to insert the fragment: document.body.insertBefore(fragment, document.body.childNodes[0]);
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...
You want this
document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With