Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda