How to add content to html body using JS?

后端 未结 8 2038
孤城傲影
孤城傲影 2020-11-28 07:19

I have many

in my html and want to add more through javascript. However, using innerHTML is just replacin
相关标签:
8条回答
  • 2020-11-28 08:15

    Working demo:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    onload = function(){
    var divg = document.createElement("div");
    divg.appendChild(document.createTextNode("New DIV"));
    document.body.appendChild(divg);
    };
    </script>
    </head>
    <body>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-11-28 08:17

    You're probably using

    document.getElementById('element').innerHTML = "New content"
    

    Try this instead:

    document.getElementById('element').innerHTML += "New content"
    

    Or, preferably, use DOM Manipulation:

    document.getElementById('element').appendChild(document.createElement("div"))
    

    Dom manipulation would be preferred compared to using innerHTML, because innerHTML simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.

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