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

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

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 Denunciar

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 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