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

146
Views
JavaScript cannot insert variable value

I'm trying to insert the value of the variable newData123 into the test attribute.

But it inserts the variable name newData123 instead of its value 456...

What am I doing wrong?

Edited

The reason why I don't directly use elm.setAttribute('test', 'newData123'); is that I need to pull the data dynamatically from another script like the below:

const newData123 = '456',
   newData456 = '789';

And that is why I need to use the template literal here in a programmatic way instead of hard code it.

const elm = document.querySelector('.test'),
  data = '123',
  newData123 = '456';
  
elm.setAttribute('test', `newData${data}`);

const check = elm.getAttribute('test');

console.log(check);
<p class="test"></p>

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

It would be much safer if you formatted all your newData variables into an object of some sort.

const data_obj = {
  newData123: '456',
  newData456: '123'
}
const data = '123'
console.log(data_obj[`newData${data}`]) // 456

const data2 = '456'
console.log(data_obj[`newData${data2}`]) // 123

Since JS is a little fuzzy with datatypes, you could even do something like this, which would require minimal refactoring:

const newData = {
  123: '456',
  456: '123'
}
let data = '123'
console.log(newData[data]) // 456

data = '456'
console.log(newData[data]) // 123
  
console.log(newData[123]) // 456

about 4 years ago · Santiago Trujillo 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!