Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Insert element at script position

Tags:

javascript

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.

like image 332
Daniel Hyuuga Avatar asked Oct 20 '25 13:10

Daniel Hyuuga


2 Answers

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.

like image 148
Teemu Avatar answered Oct 23 '25 04:10

Teemu


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>');
like image 44
Sam Samskies Avatar answered Oct 23 '25 03:10

Sam Samskies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!