Tips on getting an external JS file to write into HTML <script> tags using either vanilla JavaScript or jQuery

Can a function be written in an external javascript file linked to the index.html, which when called writes content between the <script></script> tags in the index.html file on line 18 using plain Javascript or jQuery?

EDIT: The goal is to only have one script tag in the index.html.

function writeToScriptTags() {
  // this function should write alert("Hello") to the <script></script> tags in the index.html file.
}
<!DOCTYPE html>
<html lang="en" dir="ltr>
  <head>
    <meta charset="utf-8">
    <!-- Dependencies -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" charset="utf-8"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" charset="utf-8"></script>
    <script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" charset="utf-8"></script>
    <title>CodeDragon</title>
    <link rel="stylesheet" href="/css/master.css">
  </head>
  <body>
    <div id="Dragon"></div>

    <input type="text" name="_input" value="" id="_input">
    <script src="script.js" charset="utf-8"></script>
    <script>
      // Implementation of writing alert("Hello") goes here
    </script>
  </body>
</html>

Answer №1

To execute code in a script tag that already exists, you can set its text, textContent, or innerText value to the desired code. However, the script must have been empty initially, without any text or whitespace, for it to run properly.

// Use an appropriate CSS selector to locate the correct script
// This example selects the first script it finds
var s = document.querySelector('script');
s.text = 'alert("Here")';

It might be easier to create a new script element and add the code there instead of checking whether the existing script tag has been used before.

var s = document.createElement('script');
document.head.appendChild(s);
s.text = 'alert("Here")';

Keep in mind that if the script includes a src attribute, setting the text content of the script will not execute any code as it is ignored for externally linked scripts.

Answer №2

If you're looking for a solution, consider the following approach Here is an example of how to implement this in your external.js file

function writeToScriptTags() {
  // The purpose of this function is to insert alert("Hello") into the <script></script> tags within the index.html file.
}

You can invoke functions from the external.js file by including them between the <script></script> tags in the index.html file as shown below.

$.getscript("path/to/jsFile", function() {
    writeToScriptTags()
});

I hope this example gives you some insight.

Answer №3

Here are two solutions to achieve the same result using jQuery and plain JavaScript:

jQuery solution: 
$('script').html('alert(\'Hello\')');
Plain JS solution:
document.querySelector('html').innerHTML = alert('Hello');

Remember not to add this code as plain text, as it will lose its functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Firebase data within a Bootstrap modal interface

Recently, I've been working on a website project where I'm utilizing the Firebase Realtime Database to retrieve user-inserted data and display it as Bootstrap Cards, just like in these images: Firebase Realtime Database - 1st card Firebase Real ...

What steps can you follow to allow Form Control to accept empty fields while rejecting all white space characters?

In my current project, I'm working on validating a field in a reactive form. The tricky part is that the field can be left blank as it's not mandatory, but it shouldn't consist only of white space characters. To tackle this issue, I decided ...

Implementing a read more toggle feature

I need help fixing my "read more" toggle code. Currently, when I click on a read more button for one story, it changes all other buttons to "read less". How can I update the code to only change the text for the specific button that is clicked? Here is my ...

Discover the interactive world of HTML5 Canvas on iPhone with exciting highlights triggered by touchstart or mousedown

The canvas changes to a darker color when touched and held, reverting back to normal when the touch is released. This effect is similar to how hyperlinks are highlighted on an iPhone, not like text selection. To implement this feature, I am using jQuery t ...

What is the process for generating SDF-Icons (Mapbox's specialized icons) from PNG files?

I am currently working on changing the icon color of an icon image in Mapbox. According to Mapbox documentation, the only way to do this is by using sdf-icons (https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#paint-symbol-icon-color). After hours o ...

My Javascript code is being modified by Wordpress to include '<p>' tags

Using the philantrophy theme, I incorporated sliders into a page using shortcodes and encountered an issue where p tags were automatically inserted into my javascript code. The following code snippet highlights the unwanted p tag added in my javascript: ...

Issue encountered when running NodeJs delete method test using Mocha

Currently, I am working on a billboard app to expand my knowledge of new technologies. However, I am facing some challenges while attempting to test the DELETE method of the API using Mocha. I have tried various approaches to solve this issue, but so far, ...

Using Jquery's getJson method, we can easily fetch and retrieve the appropriate JSON string by

I have the following code snippet at the beginning of the JSON url: if(isset($_GET['template']) && $_GET['template']=="blue") { $inifile_path="ctr/subthemes/blue/"; } else { $inifile_path="ctr/subthemes/fresh-n-clean/"; } Addi ...

Showing JSON information in an Angular application

Upon page load, I am encountering an issue with retrieving and storing JSON data objects in Angular scope for use on my page and in my controller. When attempting to access the value, I receive the error message: angular.js:11655 ReferenceError: data is ...

Deactivate the child division by the nth parent division

At the end of my question, I have included a dynamically created div structure with the id "forth-three-one". Now, I need to find a way to disable or hide the input inside this specific div. Directly using the id "forth-three-one" is not an option as it w ...

iOS users experiencing issues with displaced iframes when dragging

I am currently facing an issue with the iframe on my website. Whenever the Make an Appointment button is clicked, the iframe displays a contact form with multiple input fields. Although everything seems to be functioning properly, I have noticed that on i ...

Determine if two sets of arrays have the same identification numbers

Initially, my arrays are named after the different continents of the world. europe= []; northAmerica = []; southAmerica = []; asia = []; In addition to these, I also have two arrays containing some specific data. arr1 = [1,3]; arr2 = [ { country: " ...

What is the best way to conceal a set of buttons on the main page using vue.js?

I'm having trouble hiding a button-group on the main page. It should disappear when either the button moveTo(0) is clicked or when scrolling to the top of the page. show: function() { this.scrollTop = (window.pageYOffset !== undefined) ? windo ...

Adjust the style of an element when hovering over a different element

Below is the HTML code in question: <div> class="module-title" <h2 class="title" style="visibility: visible;"> <span>Spantext</span> Nonspantext </h2> </div> I am looking to change th ...

What could be causing my ul CSS to function properly in Internet Explorer but fail in Chrome?

Why does my CSS work fine on Internet Explorer but not on Chrome? The formatting doesn't show up in Chrome, appearing plain as if the CSS isn't being applied. It works when I place the css directly inside the head tag of the html, but I need it i ...

creating a div element with a height that matches its content dimensions

I'm having trouble creating a navigation bar because the outer div isn't matching the height of the unordered list inside it. I attempted using display:inline-block as well, but it didn't solve the issue. Here is the HTML: http://jsfiddle ...

Leveraging python's BeautifulSoup library, one can easily implement HTML selection

Recently, I've started diving into Automate the Boring Stuff and exploring how to create my own programs. Currently, I'm experimenting with beautiful soup's 'select' method in order to extract the value '33' from this cod ...

What is the best method for populating a text area in Pharo with HTML content?

When logging in through Pharo using an HTML form, you can utilize the method of Znclient called formAt:add: followed by a post. I'm interested to know how I can fill a textArea in an HTML form and then make a post request. Is there a specific method f ...

Having difficulties with JavaScript's if statements

I'm facing an issue with my JavaScript code that is meant to modify the value of a price variable and then display the updated price. The problem arises when I have multiple select options, as the price only reflects the ID of the last statement. Here ...

Session availability extends to subdomains, even though it may not be visible in a physical

Currently in the process of building a website Red Sec using a single account for all subdomains: Latest Updates Community Forum Personal Blog News Feed Support Us All pages share the same layout with different content by linking them to . Below i ...