Daniel Hyuuga
Daniel Hyuuga

Reputation: 466

Javascript - Insert element at script position

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.

Upvotes: 3

Views: 3309

Answers (5)

Willy Wonka
Willy Wonka

Reputation: 81

Another solution that doesn't wrap everything inside a div and that can be re-used several times without implications:

function insertHtmlToDocumentAtCurrentScriptPosition(htmlStr)
{
    var scriptTag = document.getElementsByTagName('script');
    scriptTag = scriptTag[scriptTag.length - 1];
    var parentTag = scriptTag.parentNode;
    parentTag.innerHTML += htmlStr;
}

The function takes html as string, so call it like:

insertHtmlToDocumentAtCurrentScriptPosition(`<p>Hello</p>`);

Upvotes: 0

Stefan
Stefan

Reputation: 448

You have to call the script at some point i like to use jquery to add an element http://api.jquery.com/append/ you have to say where do you want to add :

$(".div")

and what should happen there:

.append("<div>Hello</div>")

so its look like that:

$(".div").append("<div>Hello</div>")

Upvotes: 0

Sam Samskies
Sam Samskies

Reputation: 141

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>');

Upvotes: 1

Teemu
Teemu

Reputation: 23396

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.

Upvotes: 7

Stepan Tripal
Stepan Tripal

Reputation: 681

$("div.div").prepend('<div>hello</div>');

Upvotes: 0

Related Questions