Insert HTML before element in JavaScript

With this method (supported by all major browsers, including IE 4), you can take an arbitrary HTML string, and insert it anywhere in the document.

<script>
document.getElementById('heading1').insertAdjacentHTML('beforebegin', '<h3 style="text-align: center;"><strong>Adding Classes</strong></h3>');
document.getElementById('heading5').insertAdjacentHTML('beforebegin', '<h3 style="text-align: center;"><strong>Dropping Classes</strong></h3>');
document.getElementById('heading6').insertAdjacentHTML('beforebegin', '<h3 style="text-align: center;"><strong>FAQs and Hints</strong></h3>');
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *