Aaron
Aaron

Reputation: 541

Adding innerHTML positioned before the existing HTML in Javascript

Instead of this method which adds more HTML after the existing HTML of an element,

document.getElementById('div1').innerHTML += 'new html';

<div id="div1">old html new html</div>

Is there a way to insert it before the existing HTML?

document.getElementById('div1').innerHTML += 'new html';

<div id="div1">new html old html</div>

Upvotes: 2

Views: 1441

Answers (1)

Lee Taylor
Lee Taylor

Reputation: 7984

Yes, simply:

 var oldHTML = document.getElementById('div1').innerHTML;
 document.getElementById('div1').innerHTML = "New HTML" + oldHTML;

Upvotes: 5

Related Questions