I have two JS variables that contain the IDs of an HTML input element and a span element respectively.
const male1DOB = document.getElementById('male1-dob');
const male1DOBError = document.getElementById('male1-dob-error');
I want to reference these two elements in a function. Of course, one way to do it would be to pass the two element objects to the function like this:
validateElemId(maleDOB, maleDOBError);
...
function validateElemId(elem, elemError) {
// Print value of input element
console.log(elem.value);
// Print error string
console.log(elemError.innerHTML);
But since these elements share a common prefix, it would be cleaner and terser to just pass that prefix to the function as a string and then interpolate it in the function something like this:
validateElemId(maleDOB);
...
function validateElemId(elem) {
console.log(<elem>.value);
console.log(<elem>Error.innerHTML);
}
How do you do this? If I do this:
validateElemId('maleDOB')
...
function validateElemId(elem) {
console.log(`${elem}.value`);
I get the following instead of the actual value of the element:
maleDOB.value
If I do this instead:
validateElemId(maleDOB):
...
function validateElemId(elem) {
console.log(elem.value);
console.log(elemError.innerHTML);
I get the correct element value but I get an error for elemError:
Uncaught ReferenceError: elemError is not defined.