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

210
Visualizações
Passing a string variable into a function parameter in Javascript

I have a dozen or so trigger fields on a webpage that I'd like to consolidate. I'm attempting to add a 'data-target' attribute to the HTML tags that have event listeners which will correspond to the target dom object to reveal when selected.

var target = this.getAttribute('data-target');

document.querySelector('#${target}');

In this case, I want to select the dom object with the ID that matches the data-target of the variable. Is it possible to use string literals like this in Javascript?

schedule_yes.addEventListener('focus', handleReveal);

function handleReveal(target){
    var target = this.getAttribute('data-target');
    console.log(target);
    let what_date = document.querySelector('#${target}');
    console.log(what_date);


<input class="form-check-input check" type="radio" name="is_schedule" id="schedule_yes" data-target="schedule_date"/>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use a template literal instead of single quotes:

function handleReveal(target){
  var target = this.getAttribute('data-target');
  console.log(target);
  var what_date = document.querySelector(`#${target}`);
  console.log(what_date);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Naming your parameter target just to overwrite it inside your function doesn't make any sense. Also to access data attributes the DOM element has a dataset property designed specifically for the purpose.

So here's the clean version:

function handleReveal(){
  const { target } = this.dataset;
  // same as: const target = this.dataset.target;
  // same as: const target = this.getAttribute('data-target');
  console.log(target);
  const what_date = document.getElementById(target);
  console.log(what_date);
}


schedule_yes.addEventListener('focus', handleReveal);
<input class="form-check-input check" type="radio" name="is_schedule" id="schedule_yes" data-target="schedule_date"/>

<div id="schedule_date">The TARGET</div>

about 4 years ago · Juan Pablo Isaza 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