0

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);
}
5
  • Please note that the output is HTML not JS. Try creating a p element instead of a text node? document.createElement('p') and then you can style that in CSS. developer.mozilla.org/en-US/docs/Learn/… Commented Dec 9, 2021 at 15:37
  • CSS styles HTML, not JS. JS is pure code, you can't "style" it with CSS, it makes no sense. You can style your h1, your element with id="flex-box-result" etc. but styling JS is nonsense. Commented Dec 9, 2021 at 16:29
  • @JeremyThille you can style console.log with css, but it still uses HTML >_< Commented Dec 9, 2021 at 16:31
  • But it's not Javascript code itself, it's a log output Commented Dec 9, 2021 at 16:32
  • @JeremyThille but that's what I said 😭 Commented Dec 9, 2021 at 16:33

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.