passing a javascript variable to html

I am facing an issue with two files, filter.html and filter.js. The file filter.html contains a div with the id "test", while the file filter.js has a variable named "finishedHTML."

My objective is to inject the content of "finishedHTML" into the test div as html code. However, "finishedHTML" seems to be empty. How can I resolve this problem?

Source:

var finishedHTML = "<h2>Yes it works</h2>"
header {
  display: block;
  background: #A2AFBC;
  top: 0;
  height: 50px;
  position: fixed;
  width: 100%;  
  text-align: center;
}

footer {
  height: 50px;
  width: 100%;
  bottom: 0px;
  left: 0px;
  background: #A2AFBC;
  position: fixed;
}
.headerTitle {
  font-size: 2.0em;
  font-family: Verdana;
  font-weight: 100;
  color: #506B84;
  margin: 0em;
  font-weight: bold;
}

h2 {
  font-size: 3.0 em;
  color: red;
}
<html>    
<head>
    <title>title</title>
    <link rel="stylesheet" href="style.css" type="text/css" >
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" >
    <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" >
    <!--Filter.js-->
    <script language="javascript" type="text/javascript" src="filter.js"></script>
</head>
<body>
    <header>
        <span class="headerTitle">Header Text</span>
    </header>

    <div id="test" style="margin-left: 300px; padding-top: 300px;">
        <h1>This is a test text</h1>
    </div>
    <script language="javascript" type="text/javascript">
        document.getElementById('test').innerHTML = finishedHTML;
    </script>
    <footer>
    </footer>
</body>
</html>

Thank you for your assistance!

Answer №1

To ensure the variable finishedHTML functions properly, it must be declared before use. Simply declare it at any point prior to assigning the innerHTML, and it will execute as intended.

var finishedHTML = "<h2>Yes it works</h2>";
document.getElementById('test').innerHTML = finishedHTML;
header {
        display: block;
        background: #A2AFBC;
        top: 0;
        height: 50px;
        position: fixed;
        width: 100%;  
        text-align: center;
    }
    
footer {
        height: 50px;
        width: 100%;
        bottom: 0px;
        left: 0px;
        background: #A2AFBC;
        position: fixed;
    }
.headerTitle {
    font-size: 2.0em;
    font-family: Verdana;
    font-weight: 100;
    color: #506B84;
    margin: 0em;
    font-weight: bold;
    
}

h2 {
  font-size: 3.0 em;
  color: red;
  
}
<html>    
    <head>
        <title>title</title>
        <link rel="stylesheet" href="style.css" type="text/css" >
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" >
        <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" >
        <!--Filter.js-->
        <script language="javascript" type="text/javascript" src="filter.js"></script>
    </head>
    <body>
        <header>
            <span class="headerTitle">Header Text</span>
        </header>
        <!-- style="margin-left: 300px; padding-top: 300px;"-->
        <div id="test" style="margin-top: 100px;">
            <h1>This is a test text</h1>
        </div>
        
        <footer>
        </footer>
    </body>
</html>

Answer №2

<html>    
    <head>
        <title>title</title>
        <link rel="stylesheet" href="style.css" type="text/css" >
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" >
        <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" >
    </head>
    <body>
        <header>
            <span class="headerTitle">Header Text</span>
        </header>

        <div id="test" style="margin-left: 300px; padding-top: 300px;">
            <h1>This is a test text</h1>
        </div>
        <!--Filter.js-->
        <script language="javascript" type="text/javascript" src="filter.js"></script>
        <script language="javascript" type="text/javascript">
            document.getElementById('test').innerHTML = finishedHTML;
        </script>
        <footer>
        </footer>
    </body>
</html>

Placing <script> tags inside the body can help resolve any issues related to asynchronous script loading.

Answer №3

Just wanted to share that everything seems to be working perfectly for me. Thank you!

<html>    
    <head>
        <title>My Title</title>
        <link rel="stylesheet" href="style.css" type="text/css" >
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" >
        <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico" >
        <!--Filter.js-->
        <script language="javascript" type="text/javascript" src="filter.js"></script>
    </head>
    <body>
        <header>
            <span class="headerTitle">Header Text</span>
        </header>
        
        <div id="test" style="margin-left: 300px; padding-top: 30px;">
            <h1>This is a test text</h1>
        </div>
        <script language="javascript" type="text/javascript">
            var finishedHTML = "<h2>Yes it works</h2>";
            console.log(finishedHTML);
            document.getElementById('test').innerHTML = finishedHTML;
        </script>
        <footer>
        </footer>
    </body>
</html>

Answer №4

Reposition

document.getElementById('test').innerHTML = finishedHTML;
in the filter.js file.

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

Prevent jQuery UI default styling from being applied

I'm curious about how to prevent jQuery UI from adding any classes when initializing $.tabs(). This is the structure of my HTML: <link href="smoothness/jquery-ui-1.8.20.custom.css" rel="stylesheet" type="text/css" /> ... <link href="estilos ...

The application is unable to recognize the CSS file

I am facing an issue where the design of my app is not displaying, even though the CSS file is located in the same folder. I'm unsure about what mistake I might have made! import React from 'react'; import classes from './Burger.css&ap ...

Manipulate the value of the <input> element when focused through JavaScript

After I focus on the input field, I was expecting to see Bond-Patterson, but instead, I am only getting Bond. What could be causing this discrepancy and how can it be fixed? $('input[name="surname"]').attr("onfocus", "this.placeholder='Bo ...

Is there a way to tally ng-required errors specifically for sets of radio buttons?

Currently, I am working on a form in AngularJS that includes groups of radio buttons. One of my goals is to provide users with an error count for the form. However, I have encountered a peculiar issue: After implementing this code to keep track of errors ...

Tips for incorporating WinBox JS into Angular applications

I've been experimenting with the WinBoxJS JavaScript library, and I'm familiar with using it in plain JS. However, I'm now attempting to integrate it into my Angular project. Can anyone guide me on how to achieve this? https://www.npmjs.com/ ...

When a React CSS class is deployed to a production server, it may be automatically

I've encountered a strange CSS issue while working on my React project. One specific section of the JSX <div> has a class with style properties defined in the main .css file. During local development, everything appears as expected. However, aft ...

What is the reason behind Chrome Dev Tools not automatically adding the parentheses when a method is selected?

In the console of Dev Tools, if you have an object named x with three methods/functions - a(), b(), and c(i, j, k), why doesn't it automatically insert the parentheses, along with the correct spaces for the parameters (similar to eclipse for Java) whe ...

Issue Installing Npm Package (detected 23 security vulnerabilities)

My attempt to install the package resulted in an error message. How can I resolve this issue? ...

Implementing a Searchable Autocomplete Feature within a Popover Component

Having an issue saving the search query state. https://i.stack.imgur.com/HPfhD.png https://i.stack.imgur.com/HbdYo.png The problem arises when the popover is focused, the searchString starts with undefined (shown as the second undefined value in the ima ...

Unexpected behavior with VueJS Select2 directive not triggering @change event

Recently, I implemented the Select2 directive for VueJS 1.0.15 by following the example provided on their official page. However, I am facing an issue where I am unable to capture the @change event. Here is the HTML code snippet: <select v-select="ite ...

What is the best way to save the value returned by a foreach loop into an array and then send two responses

After attempting to store the doctor details in an array and display the appointment and doctor Name Value response, I encountered a problem. The Appointment value is successfully achieved, but the doctor Name Value appears empty even though it shows in th ...

TypeOrm is struggling to identify the entities based on the directory path provided

Currently, I am utilizing TypeORM with NestJS and PostgreSql to load entities via the datasource options object. This object is passed in the useFactory async function within the TypeORM module as shown below: @Module({ imports: [TypeOrmModule.forRootAsy ...

Instructions for returning a function from within another function and then displaying it upon return

My current state: constructor(props) { super(props); this.state = { temperatureConversion: '', Here is the function I'm using: handleChange = async (value) => { this.setState({ value }); await Axios.ge ...

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

Why am I encountering difficulties connecting to the Socket IO object in Node.js using Express?

Encountering a strange issue on the remote server side where everything works fine locally with a self-signed cert over https. However, when moving the code to the server, it works locally but not remotely. A node app is created and hosted on the server u ...

Troubleshooting Vercel and Express DELETE request cross-origin resource sharing problem

Currently, I am in the process of developing an API using Vercel and ExpressJS. The GET and POST endpoints are functioning properly, however, I encountered an issue with the DELETE endpoint. When attempting to access the endpoint from my client-side JavaSc ...

Utilize Material-UI's <Autocomplete /> feature to conduct searches using multiple parameters

Recently, I started delving into mastering Material UI and something has been on my mind. We are working with an array of objects as follows: const top100Films = [ { label: 'The Shawshank Redemption', year: 1994 }, { label: 'The Godfath ...

Struggling to eliminate the unseen padding or white space preventing the text from wrapping under the button

Just starting out with html and css and could use some assistance with a small issue I've come across. While redesigning a website, I have a three-button form (Donate, Find, Subscribe). I'm trying to get the paragraph underneath the Donate and Fi ...

C#: Issues with loading static content in MVC on various environments with IIS

Within my C# MVC 4.5 Website, I recently introduced a new folder to host CMS-type applications separately from the main site. While everything seemed fine during local testing, issues arose after deploying the updates to the DEV environment. A closer look ...

My program contains redundant sections that are being repeated multiple times, and I am unsure of how to remedy this issue

This particular payment gateway relies on a paid market for processing transactions. Unfortunately, there seems to be an issue where multiple error messages are being triggered during the payment verification process. The errors include: ❌ | An error h ...