How to add content to html body using JS?

后端 未结 8 2037
孤城傲影
孤城傲影 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 07:50

    You can use

    document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)
    

    or

    document.getElementById("parentID").innerHTML+= "new content"
    
    0 讨论(0)
  • 2020-11-28 08:00

    In most browsers, you can use a javascript variable instead of using document.getElementById. Say your html body content is like this:

    <section id="mySection"> Hello </section>
    

    Then you can just refer to mySection as a variable in javascript:

    mySection.innerText += ', world'
    // same as: document.getElementById('mySection').innerText += ', world'
    

    See this snippet:

    mySection.innerText += ', world!'
    <section id="mySection"> Hello </section>

    0 讨论(0)
  • 2020-11-28 08:05

    I think if you want to add content directly to the body, the best way is:

    document.body.innerHTML = document.body.innerHTML + "bla bla";
    

    To replace it, use:

    document.body.innerHTML = "bla bla";
    
    0 讨论(0)
  • 2020-11-28 08:08

    Try the following syntax:

    document.body.innerHTML += "<p>My new content</p>";
    
    0 讨论(0)
  • 2020-11-28 08:09

    I Just came across to a similar to this question solution with included some performance statistics.

    It seems that example below is faster:

    document.getElementById('container').insertAdjacentHTML('beforeend', '<div id="idChild"> content html </div>');

    InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML.

    Reference: 1) Performance stats 2) API - insertAdjacentHTML

    I hope this will help.

    0 讨论(0)
  • 2020-11-28 08:10

    Just:

        document.getElementById('myDiv').innerHTMl += "New Content";
    
    0 讨论(0)
提交回复
热议问题