foxer
foxer

Reputation: 901

Adding tags dynamically to HTML at the right place

Somewhere in the HTML file we have this:

<script SRC="story_content/user.js" TYPE="text/javascript"></script>

What if we want to dynamically (Javascript is preferred JQuery is accepted) add another script tag or CSS link right after it.

Explanation: We need to select the script tag by SRC and we need to add the tags after the script tag.

Here is the tags we need to add after the script tag

<link rel="stylesheet" href="../../../sources/main.min.css" data-noprefix />
<link rel="stylesheet" href="html5/data/css/output.min.css" data-noprefix />
<script data-main="app/scripts/init.generated" src="../../../sources/app.min.js"></script>

Upvotes: 0

Views: 109

Answers (1)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

You could use query selector to acheive the target in pure js like:

var source_name = "story_content/user.js"              // path of file

var add_to = document.querySelector(`script[src=${source_name}]`);

Once, add_to is store, you should be able to add the tag, like:

var to_be_added_tag = document.CreateElement("script");
to_be_added_tag.setAttribute("src", src_path_of_your_file); // src_path_of_your_file is variable, value of src attribute

add_to.after(to_be_added_tag);   

*Note:- after is used to add element after some node. refs

Upvotes: 1

Related Questions