Add HTML elements dynamically with JavaScript inside DIV with specific ID

前端 未结 2 568
清酒与你
清酒与你 2021-01-01 12:19

Ok, people, I need your help. I\'ve found some code here on Stackoverflow (can\'t find that link) which generate HTML code dynamically via JS. Here is code:

         


        
2条回答
  •  北海茫月
    2021-01-01 12:51

    All you need to do is change the last line. This will add the created element as the last child of the div:

    document.getElementById("generate-here").appendChild(fragment);     
    

    This will add the created element as the first child of the div:

    var generateHere = document.getElementById("generate-here");
    generateHere.insertBefore(fragment, generateHere.firstChild);
    

    You can also use innerHTML to just replace everything with new text (as you do in your create function). Obviously this one doesn't require you to keep the create function because you need an html string instead of a DOM object.

    var generateHere = document.getElementById("generate-here");
    generateHere.innerHTML = '';
    

提交回复
热议问题