Home > Enterprise >  use javascript variable in html script
use javascript variable in html script

Time:10-29

I have an AJAX function in my JavaScript like so

function getWeather(countryName) {
    const monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
    ];

    let dateObj = new Date();
    let month = monthNames[dateObj.getUTCMonth()];
    let day = dateObj.getUTCDate() - 1;
    let year = dateObj.getUTCFullYear();

    let newDate = `${month} ${day}, ${year}`;
    
    $.ajax({
        url: "assets/geojson/countryBorders.geo.json",
        type: "GET",
        dataType: "json",
        data: {
            
        },
        success: function(result) {
.... etc

Within my HTML modal for displaying the weather per country, I would like to include things such as the date.

Is there any way to use the Javascript variable newDate in the HTML script?

something like ....?

 <div >
          <h6 id="capitalCity" ></h6>
          <hr>
          <ul >
              <p  id="newDate"></p>

CodePudding user response:

Elaboration on Franco A. Torreses answer this will be your javascript

function getWeather(countryName) {
    const monthNames = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
    ];

    let dateObj = new Date();
    let month = monthNames[dateObj.getUTCMonth()];
    let day = dateObj.getUTCDate() - 1;
    let year = dateObj.getUTCFullYear();

    let newDate = `${month} ${day}, ${year}`;
    document.getElementById('newData').textContent = newDate

And your HTML will stay the same. document.getElementById('newData') grabs the element from DOM and .textContent sets it's text to whatever is after =. This is also superior to using .innerHTML as .innerHTML it allows for injections.

If you are after using variables in HTML, you could take a look into either frontent frameworks such as React, VueJS, Angular that allow just using {variable} or some other backend languages such as PHP.

Edit

Regarding innerHTML. As was stated in comments by @tacoshy "innerHTML poses a security issue as it is open for XSS injections if the injected code isn't validated" This is because textContent does not let you insert HTML elements (opposed to .innerHTML), but you don't have to worry about that if your application does not have any user input. Also it's more performant as it does not require DOM-reparse.

CodePudding user response:

To insert a value inside a DOM element:

document.getElementById('newData').textContent = 'the value'

The document method getElementById retrieves the DOM element by its id, which in this case is newData. The DOM element method textContent changes the DOM element's text.

CodePudding user response:

const dateOptions = { year: 'numeric', month: 'long', day: 'numeric' };
const dateFormatter = new Intl.DateTimeFormat( 'en-US', dateOptions ).format;

document.getElementById('newData').textContent = dateFormatter( new Date() );

// Result = October 28, 2022

You can use the browser native function Intl.DateTimeFormat to format your date as needed without having to run lots of logic or using 3rd party code.

  • Related