0

I want to be able to create a JavaScript element where the script is included.

Example:

<script src='addDiv.js'></script>

The addDiv.js simply adds a customized div as below:

var element = document.createElement("div");
element.setAttribute("id", "myspecialdiv");
document.body.appendChild(element);

I want to add this div wherever this script is included instead of at the end of body. Is there a way to achieve this ?

Thanks

  • just target the script tag by src content or give it a `id` and insert there – Christian Carrillo Jul 02 '20 at 02:15
  • You could pass params from the script tag to the script code, for example an id and in this way add the div just next to script tag. Read SO question https://stackoverflow.com/questions/5292372/how-to-pass-parameters-to-a-script-tag – Mario Jul 02 '20 at 02:25
  • How can I do that ? How can I refer the script tag ? – user3822006 Jul 02 '20 at 02:46

1 Answers1

1

In most modern browsers you can use document.currentScript;

<script>
  function replaceScript(el, text) {
    let p = document.createElement('p')
    p.innerText = text;    
    el.replaceWith(p);
  }
</script>

<script>  
  replaceScript(document.currentScript, 'Test 1');
</script>

<script>  
  replaceScript(document.currentScript, 'Test 2');
</script>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • But this means I will have to include at least two scripts, one to add replaceScript functions, and another to call that function. Is there a way to do this by just one ? – user3822006 Jul 02 '20 at 02:41
  • Can just as easily be done in one. I only did it this way to show it working – charlietfl Jul 02 '20 at 02:41