Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!