javascriptoutputcreatetextnode

Javascrit .createTextNode output is giving errors


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

var h1 = document.createElement("p");
h1.setAttribute("id", "mainText")
var mainText = document.createTextNode("You are ", ageYears, " years, ", ageMonths, " 
months and ", ageDays, " days old.");
h1.appendChild(mainText);
document.getElementById("new-age").appendChild(h1);

When I run my code, it only outputs the first part, "You are". Is there any way to output the entire message.


Solution

  • In JavaScript you use + instead of . to concatenate strings.

    working example

    var h1 = document.createElement("p");
    h1.setAttribute("id", "mainText");
    let ageYears = 20;
    let ageMonths = 12
    let ageDays = 24;
    var mainText = document.createTextNode("You are " + ageYears + " years, " + ageMonths  + " months and " + ageDays + " days old.");
    h1.appendChild(mainText);
    document.getElementById("new-age").appendChild(h1);
    <div id="new-age"></div>