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"/>
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);
}
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>