javascriptdominnerhtml

How to append to innerHTML instead of replacing its contents


I know we can change the content of, e.g.,

<div id="whatEverId">hello one<div> by using:

document.getElementById("whatEverId").innerHTML="hello two";

Is there a way (using .innerHTML()) I can add contents to the div instead of replacing it? So I can get, for example,

<div id="whatEverId">hello one hello two<div>


Solution

  • Use the += (addition assignment) operator:

    <div id="whatever">hello one</div>
    <script>
    document.getElementById("whatever").innerHTML += " hello two";
    </script>