-1

I have an HTML like this

<div id="content">
    <h1>Shop Sample</h1>
    <h2>View HTML-Source to see the embedded js</h2>

    <script src="js/faq_embd.js"></script>
    <div id="response-area">

    </div>
</div>

Now the faq_embd.js is supposed to render html right under its own <script> Tag.

In js, how do I find out where the Tag is and how do I append under it?

Saphire
  • 1,812
  • 1
  • 18
  • 34
  • Take a look at this answer, it describes how to work with script tag references very well: https://stackoverflow.com/a/22745553/6524598 – Lesleyvdp Aug 30 '18 at 11:49
  • I don't think such kind of built-in function available which can let you know about location of element – Ayaz Ali Shah Aug 30 '18 at 11:49
  • 1
    Possible duplicate of [How may I reference the script tag that loaded the currently-executing script?](https://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script) – Fcmam5 Aug 30 '18 at 11:50
  • This really sounds like an [XY problem](http://xyproblem.info/). Please explain whole issue in more detail – charlietfl Aug 30 '18 at 11:50
  • 1
    I would suggest to not pick the place to render based around where the script tag appears, but target the div instead. – Shilly Aug 30 '18 at 11:51

2 Answers2

0

You can use the following. This will set a paragraph right below the script. You can verify by checking the DOM

document.getElementsByTagName("script")[1].insertAdjacentHTML('afterend', '<p id="idChild"> content html </p>');
<div id="content">
    <h1>Shop Sample</h1>
    <h2>View HTML-Source to see the embedded js</h2>

    <script src="js/faq_embd.js"></script>
    <div id="response-area">

    </div>
</div>
95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
0

You can locate the current script element using document.currentScript. Note that Internet Expolorer does not support it at all (view compatibility table at https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript), so a simple way to get the current script element in a corss-browser way is to give your tag a fixed id, then locate it with document.getElementById().

For performace reasons, before using the DOM, try to retrive the current script tag with document.currentScript.

As an example, having an html like this

<div id="content">
  <h1>Shop Sample</h1>
  <h2>View HTML-Source to see the embedded js</h2>
  <script id="script-id" src="js/faq_embd.js"></script>
  <div id="response-area"></div>
</div>

You could use this code to create a new paragraph just under the current script tag:

var yourScript = document.currentScript || document.getElementById("script-id");
var yourParagraph = document.createElement("p");
if (yourScript.nextSibling){
  yourScript.parentNode.insertBefore(yourParagraph, parentGuest.nextSibling);
} else {
  yourScript.parentNode.appendChild(yourParagraph);
}