I created a website where it tells you your age. I use document.createTextNode to store the output but the output is not working properly. Here is the output code
JavaScript
x
7
1
var h1 = document.createElement("p");
2
h1.setAttribute("id", "mainText")
3
var mainText = document.createTextNode("You are ", ageYears, " years, ", ageMonths, "
4
months and ", ageDays, " days old.");
5
h1.appendChild(mainText);
6
document.getElementById("new-age").appendChild(h1);
7
When I run my code, it only outputs the first part, “You are”. Is there any way to output the entire message.
Advertisement
Answer
In JavaScript you use +
instead of .
to concatenate strings.
working example
JavaScript
1
8
1
var h1 = document.createElement("p");
2
h1.setAttribute("id", "mainText");
3
let ageYears = 20;
4
let ageMonths = 12
5
let ageDays = 24;
6
var mainText = document.createTextNode("You are " + ageYears + " years, " + ageMonths + " months and " + ageDays + " days old.");
7
h1.appendChild(mainText);
8
document.getElementById("new-age").appendChild(h1);
JavaScript
1
1
1
<div id="new-age"></div>