What could be causing this JS file to not impact the DOM as expected?

Currently, I am delving into the world of JavaScript and trying to gain a better understanding of how to manipulate the DOM on my own. Throughout this learning process, I have encountered a puzzling situation that I am seeking assistance with.

The following code snippet represents an example of HTML markup:

<html>
  <body>
    <h1>A heading</h1>
    <div id="myDIV"></div>
    <script type="text/javascript" src="thejs.js"></script>
    <script type="text/javascript">
      document.getElementById("myDIV").innerHTML="<p>Try this one comes from script inside html source</p>"
    </script>
  </body>
</html>

My expectation is to achieve a similar outcome by using an external JavaScript file that is linked within the script tags. The linked file contains the following code:

document.getElementById("myDIV").innerHTML="<p>While this one comes from a separate JS file</p>";

However, I am facing a roadblock as nothing seems to happen when I run the code. I understand that this issue might appear trivial, and I sincerely apologize for any oversight on my part.

Answer №1

The initial script executes and changes the content of the div to "While this one originates from a separate source…"

Following that, a short period of imperceptible time elapses before the second script kicks in and alters the content of the div to "Try this one generated by script…".

To have both paragraphs displayed simultaneously, you must add (using +=) the new data instead of replacing it.

Nevertheless, repeatedly adding chunks of HTML with innerHTML += may lead to complications (it is inefficient because the entire batch of DOM has to be reconstructed, potentially removing any inline event handlers), so it is often advisable to utilize the insertAdjacentHTML method instead.

Answer №2

The result varies depending on the order in which you load the external JavaScript file. If you load it before the embedded script in your HTML document, the external file will be overridden by the embedded script and will have no impact. However, if you load the external JavaScript file after the embedded script, it will function as intended.

<html>
  <body>
    <h1>Heading</h1>
    <div id="myDIV"></div>
    <script type="text/javascript" src="thejs.js"></script>
    <script type="text/javascript">
      document.getElementById("myDIV").innerHTML="<p>Content from script inside HTML</p>"
    </script>
    <script type="text/javascript"  src="external.js"></script>
  </body>
</html>

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

Navigating through a Single Page Application (SPA) can be achieved without

Can the CSS (Level 4) @document rule handle URLs that have the # symbol or include query parameters? For those who are not familiar with this topic Currently, only Firefox supports this feature with the @-moz-document prefix. If other browsers start supp ...

Encountering an incorrect number of parameters for "undefined" during the deployment of a smart contract

I am facing an issue while attempting to deploy my first Voting contract on the testRPC. The error seems to arise from the arguments parameter in the code snippet below. When I tried passing an empty array, it gave an error stating "Got 0 expected 1!". Si ...

Guide to retrieving PDFs and images from a Spring Application as an API response and manipulating the data using JS/React

For my current project, I am working on a Spring Boot and React application where I need to create an API that takes the file name as input and returns the file content in Java/Spring Boot. The goal is to display the content in a new browser tab. Below is ...

Tips for specifying the "url" parameter in xmlhttp.open() for utilizing Ajax in communication with node.js

server.js has the ability to generate a random number. I am trying to retrieve a random number from the server and utilize xmlhttp to send a request. However, the string value remains unchanged when I visit http://localhost:3000/index.html. What could be c ...

How can I determine if my clients are utilizing the CDN or NPM versions of my JavaScript library?

At this moment, I'm contemplating releasing an open-source version of my library on NPM. My main concern is figuring out how to track the usage of my CDN or NPM by clients. Is there a method available to achieve this? ...

Form with several file selection points

I am working on an application that features a dynamic form capable of uploading files to different individuals simultaneously. Each person is assigned a unique input file and has the option to add up to 2 additional dynamic inputs. <div id="InputsWra ...

Updating Sailsjs Localization Settings

After working with Sails.js for a while, I am interested in finding out if it is possible to manually adjust the localization from the controllers based on the URL. For example, accessing http://example.com/en would display the English version, while http ...

Is the new mui LoadingButton not available in the latest version?

According to the material UI documentation found at here, you are supposed to import LoadingButton from '@material-ui/lab/LoadingButton'; However, I am unable to locate this folder within mui/lab and the import statement is resulting in an erro ...

Validate selected checkbox using JavaScript

Is there a way for me to achieve real-time updates when checking and unchecking multiple checkboxes in a list? Here's the code snippet I currently have: window.onload = function () { var input = document.getElementById('listTaxi'); fu ...

javascript Incorrectly using location.reload will not refresh the page as intended

My goal is to refresh a page every time a user clicks a button so the page reverts back to its original source code. However, I am facing an issue where the location.reload() function is being executed after the code instead of at the beginning. btn.addEve ...

What is the best way to stack several elements on top of each other?

<div class="parent"> <div class="child" id="child-A"> <div class="child" id="child-B"> <div class="child" id="child-C"> </div> The main concept here ...

How can I specify the exact width for Bootstrap 3 Progress Bars?

I have a single page that displays all my files in a table format, and I also have the count of open and closed files. My goal is to represent the percentage of closed files using a progress bar. The width of the progress bar should change based on this p ...

Utilizing a numeric array as an associative array in JavaScript

Within a Javascript context, I am tackling an array of objects named users. Accessing users[1].name allows me to retrieve the user's name. I am aiming to utilize the user ID as the index instead of relying on an incrementing counter. For instance, in ...

Cross-Site Scripting: Building a JavaScript object with the help of PHP's json_encode

Is this code 100% secure against XSS attacks? If not, could you provide an example of a malicious string that could make it vulnerable? <html> <body> <script> <?php $bad = "malicious string. Please provide exampl ...

Create a variable to store the sum value when iterating through a range using jQuery's

Currently, I am in the process of developing a specialized calculator that requires me to calculate the sum of variables within my jQuery.each loop for a specific range from 0 to 4 (equivalent to 5 years). While I have come across several informative reso ...

Selecting a webpage from a dropdown list to display its specific content within an iframe

I have a dropdown menu similar to this: <form name="change"> <SELECT NAME="options" ONCHANGE="document.getElementById('frame1').src = this.options[this.selectedIndex].value"> <option value="">Choose</option> <opti ...

Storing data in MongoDB upon the emission of a Socket.io event

In my project, I am using a MEAN stack and Socket.io to retrieve images from the real-time Instagram API. The current setup is functioning well, but now I want to store image data in a MongoDB database to maintain a record of images based on locations, rat ...

What is the best way to swap out an icon based on the chosen option?

Here is my code: $('#mySelect').on('change', function() { var value = $(this).val(); $(".title").html(value); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href=" ...

Ways to verify whether a callback function supplied as a parameter in Javascript has any arguments

My task involves implementing the following: doSomething .then(success) .catch(failure); The success and failure functions are callbacks that will receive their value at runtime (I am developing a module). Therefore, I need to ensure that the fa ...

Interpret the JSON reply

Could someone please explain why my function B() is not responding? <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/ja ...