Skip to content Skip to sidebar Skip to footer

How To Create And Append Multiple Dom Elements Efficiently

I'm building 10 buttons on the DOM and want to see if there is a more efficient way of building them because it seems strange to be calling createElement and appendChild 10 times.

Solution 1:

You can optimize your code by reusing the container variable and moving

document.getElementsByTagName('body')[0].appendChild(container);

after the loop

functionmakeAlertButtons () {
  var container = document.createElement("div")
  container.setAttribute('id', "container")
 
  for (var x = 1; x <=10; x++) {
    var butt = document.createElement("button")
    butt.appendChild(document.createTextNode(x))
    container.appendChild(butt)
  }

  document.getElementsByTagName('body')[0].appendChild(container);
  container.addEventListener('click', function (e) {
    alert(e.target.textContent)
  })
}

makeAlertButtons();

Solution 2:

"more efficient"? It would be more efficient at execution time if the DOM was just built with HTML. If you want the JavaScript to be more efficient, then you'll want to cache your JavaScript in the Client's Browser, by using an external <script type='text/javascript' src='yourJavaScriptPage.js'></script> tag like that in your <head>. I'm including some code here that may teach you something:

var pre = onload, doc, bod, htm, C, T, E, makeAlertButtons; // if using technique on multiple pages change pre var
onload = function(){ // window.onload Eventif(pre)pre(); // if previous onload execute it

doc = document; bod = doc.body; htm = doc.documentElement;
C = function(e){
  return doc.createElement(e);
}
T = function(n){
  return doc.getElementsByTagName(n);
}
E = function(id){
  return doc.getElementById(id);
}
makeConsoleButtons = function(count){
  var container = C('div');
  container.id = 'container';
  for(var i=1,l=count+1; i<l; i++){
    var butt = C('input');
    butt.type = 'button'; butt.value = i;
    butt.onclick = function(){ // note lazy style will overwrite - but it's faster to typeconsole.log(this.value); // alert can create problems in old IE
    }
    container.appendChild(butt);
  }
  bod.appendChild(container);
}
makeConsoleButtons(10);

} // end window.onload

Hope you learned something.

Post a Comment for "How To Create And Append Multiple Dom Elements Efficiently"