4

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.

4
  • Why you want to load from js? Is there any event there? Commented Dec 11, 2014 at 8:04
  • @vijay4vijju there is no particular event there. I'm just curious on how most of javascript embeds works, like they embed a video player or a chat. Commented Dec 11, 2014 at 8:08
  • and avoid giving class name like "div" to a div .. use some specific class names .. Commented Dec 11, 2014 at 8:09
  • Related: stackoverflow.com/questions/38947554 and stackoverflow.com/questions/1533568 Commented Aug 3, 2019 at 10:32

5 Answers 5

8

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.

Sign up to request clarification or add additional context in comments.

9 Comments

Yes this answers my question. Thank you! So script = document.scripts[document.scripts.length - 1] is needed in order to determine the parent element of the script
@DanielHyuuga Actually document.scripts is a collection of all scripts within the document. This collection is updated every time a new script is loaded/parsed during the page parsing. This way the last member of the collection always refers to the currently running script, if it is not loaded asynchronously. script.parentElement refers to the element containing the script tag itself.
I see, what if the script is loaded by async method?
When running an asynchronoulsy loaded script, the last member of document.script might refer to a different script. As long as the script itself is loaded synchronously, you can rely it finds "himself" as a last member of document.scripts. This means really running the script immediately after load, in event handlers you can't rely on this. You could put the lines above into an IIFE, that'll make sure the lines are executed, and also keeps some unnecessary variables out of the global namespace.
would be adding an ID to the script tag help?
|
1

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

Comments

1

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

Comments

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

Comments

0

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>")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.