Home > Mobile >  Javascrit .createTextNode output is giving errors
Javascrit .createTextNode output is giving errors

Time:12-18

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.

CodePudding user response:

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>

CodePudding user response:

Since document.createTextNode receives just one parameter as data, you should change your document.createTextNode like below code to generate one string with your data:(in your code because you are usign , to concatenate strings, actually you are passing multiple strings to document.createTextNode and it reads just the first argument and ignores other arguments)

var mainText = document.createTextNode("You are "   ageYears   " years, "   ageMonths   "months and "   ageDays   " days old.");

or:

var mainText = document.createTextNode(`You are ${ ageYears} years, ${ageMonths} months and ${ageDays} days old.`);

here is an example:

const ageYears = 30;
const ageMonths = 10;
const ageDays = 22;

function appendText() {
  let p = document.createElement("p");
  let mainText = document.createTextNode(`You are ${ ageYears} years, ${ageMonths} months and ${ageDays} days old.`);

  p.appendChild(mainText);
  document.getElementById("new-age").appendChild(p);
}

document.getElementById('appendBtn').addEventListener('click', appendText)
<div id="new-age"></div>
<button id="appendBtn">append text</button>

  • Related