Append something at the beginning of innerHTML

InnerHTML allows us to replace the div content or append something to its end.

In some cases, however, we may want to append something at the beginning of innerHTML content.

To do this, we can use a simple trick:

  • Grab the current element’s content.
  • Append the new content and add the old one at its end (the one we got before).

Here’s an example:

<div id="myContent">It's my content.</div>

<script>
    var oldContent = document.getElementById('myContent').innerHTML;
    var newContent = 'Hello! ';

    document.getElementById('myContent').innerHTML = newContent + oldContent;
</script>

Output:

Hello! It’s my content.