简体   繁体   中英

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.

<script>
function makeAlertButtons () {
  var container = document.createElement("div")
  container.setAttribute('id', "container")
  document.getElementsByTagName('body')[0].appendChild(container)
  for (var x = 1; x <=10; x++) {
    var butt = document.createElement("button")
    butt.appendChild(document.createTextNode(x))
    document.getElementById("container").appendChild(butt)
  }
  document.getElementById("container").addEventListener('click', function (e) {
    alert(e.target.textContent)
  })
}
makeButtons()
</script>

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

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

after the loop

 function makeAlertButtons () { 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();

"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 Event
if(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 type
      console.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.

I used this answer for another question but since basically they are same, I will post it here too.

Using an string to set innerHTML property on the element is the most efficient way to create multiple elements, because we will be deleting the creation of elements to the browser:

const el = document.createElement('div');

el.innerHTML = `
<h1>Page Title</h1>
<p>Lorem, ipsum dolor.</p>
<input value="Lorem ipsum dolor sit amet." >
<button id="btn">Click Me</button>
`;

const root = document.querySelector('#app');
root.appendChild(el);

It is supported modern browsers. Faster than manually iterating over elements. Plus it is way more cleaner than creating those elements programmatically.

You can use an existing the element. Just select the element and insert the content:

document.querySelector('#app').innerHTML = `
<h1>Page Title</h1>
<p>Lorem, ipsum dolor.</p>
<input value="Lorem ipsum dolor sit amet." >
<button id="btn">Click Me</button>
`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM