Home > OS >  How to import javascript variables into CSS and style them?
How to import javascript variables into CSS and style them?

Time:12-12

I'm quite new to javascript. I'm trying to create a website where you can input when you were born and find out your age in days. My output (variable) is also in JS, so how do I import it and style it in CSS?

Here's the Javascript code:

function ageInDays() {
  // variables
     var birthYear = prompt("What Year Were You Born In?");
     var ageInDayss = (2021 - birthYear) * 365;
     var textAnswerYikes = "Yikes... that's old"

 // variable CSS

 //text
    var h1 = document.createElement('h1');
    var textAnswer = document.createTextNode("You are "   ageInDayss   " days old. "   
    textAnswerYikes)
    h1.setAttribute('id', 'ageInDays');
    h1.appendChild(textAnswer);
    document.getElementById('flex-box-result').appendChild(h1);
}

CodePudding user response:

I assume what your 'import' means is having your h1 inside the HTML. If so, you can simply just append your h1 into the HTML body or any other HTML element you wish to have inside (e.g. div).

Your JavaScript file:

//text
   var h1 = document.createElement('h1');
   // add inner text to your h1 using string template literal.
   h1.innerText = `You are ${ageInDayss} days old. ${textAnswerYikes}`;
   h1.setAttribute('id', 'ageInDays');

   document.body.append(h1) // <- append your h1 into HTML body or other HTML element
   document.getElementById('flex-box-result').appendChild(h1);

To style your h1, you just need to select the ID that you have assigned to it (ageInDays) and style it in your CSS file.

Your CSS file:

#ageInDays {
 /* your CSS styling code goes here */
}

Hope this answer your questions.

  • Related