create/append node vs innerHTML

后端 未结 7 2191
情歌与酒
情歌与酒 2021-01-05 18:40

Does anyone have a good reason to use one over the other? As far as I can tell, create/append node simply prevents you from creating invalid code, while innerHTML allows you

相关标签:
7条回答
  • 2021-01-05 19:18

    DOM MANIPULATION IS WAY FASTER IF YOU USE THIS TRICK!.

    This is slow:

    var target = document.getElementById('whatever');
    for (a = 0; a<10000; a++) { 
    var newnode = document.createElement('div'); 
    newnode.textContent = a;
    target.appendChild(newnode) }
    

    This is fast:

    var target = document.createElement('span')
    for (a = 0; a<10000; a++) { 
    var newnode = document.createElement('div'); 
    newnode.textContent = a;
    target.appendChild(newnode) }
    document.getElementById('whatever').appendChild(target);
    

    The first example appends the newly created node to a node that already is contained inside the body so a refresh is made each time.

    The second example appends newly created nodes to a "buffer" node that is not inside the scope of the body, so no refresh is made until you place the buffer node inside the scope of the body. Try it yourself!.

    0 讨论(0)
提交回复
热议问题