Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting HTML elements with JavaScript

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]); 
like image 412
Robin Rodricks Avatar asked May 02 '09 09:05

Robin Rodricks


2 Answers

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:

  1. You can use native DOM methods for insertion such as insertBefore, appendChild etc.
  2. You have access to the actual DOM nodes before they're inserted; you can access the fragment's childNodes object.
  3. Using document fragments is very quick; faster than creating elements outside of the DOM and in certain situations faster than innerHTML.

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...

like image 192
James Avatar answered Sep 27 '22 22:09

James


You want this

document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' ); 
like image 20
Šime Vidas Avatar answered Sep 27 '22 20:09

Šime Vidas