Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda