How do I insert element at script location (not to rely on div's id or class), for example
<div class="div">
<script src='//remotehost/js/addDivSayHello.js'></script>
</div>
where addDivSayHello.js will insert div child <div>hello</div>, result example:
<div class="div">
<div>hello</div>
<script src='//remotehost/js/addDivSayHello.js'></script>
</div>
I tried searching inside Stackoverflow but found nothing.
You can use insertBefore method. Something like this:
var div = document.createElement('div'), // Create a new div
script = document.scripts[document.scripts.length - 1]; // A reference to the currently running script
div.innerHTML = 'Hello'; // Add some content to the newly-created div
script.parentElement.insertBefore(div, script); // Add the newly-created div to the page
A live demo at jsFiddle. Notice, that you can use external scripts as well.
You could use insertAdjacentHTML: https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML
var node = document.querySelector('script[src="js/addDivSayHello.js"]');
node.insertAdjacentHTML('beforebegin', '<div>hello</div>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With