Skip to content Skip to sidebar Skip to footer

How Can I Pass A Dynamic Variable To Function In JS?

Attempting to pass ids dynamically breaks function:

Send us an email<

Solution 1:

Build just the selector param dynamically...

let qS = document.querySelector(`#${idx}`);

Solution 2:

This will help you:

function mailTo(...items)
{
console.log(items[0].id);
}
<p id="email1" onclick="mailTo(this,'com','abc','info','My Website','I have a question for you: ')">Send us an email</p>
<p id="email2" onclick="mailTo(this,'org','xyz','support','My Other Website','I want to report a problem with your website.')">Report Website Problems</p>

Solution 3:

If you change

    let qS = `document.querySelector('#${idx}')`;

to

    let qS = this;

your code works. But you don't need to supply the id to query for the element since you can access it with this.


Post a Comment for "How Can I Pass A Dynamic Variable To Function In JS?"