Categories
JavaScript Answers

How to pass parameters in JavaScript onClick event?

Spread the love

To pass parameters in JavaScript onClick event, we set the onclick property of each element to its own click handler.

For instance, we write

for (let i = 0; i < 10; i++) {
  const link = document.createElement("a");
  link.setAttribute("href", "#");
  link.innerHTML = i.toString();
  link.onclick = () => {
    onClickLink(i.toString());
  };
  div.appendChild(link);
  div.appendChild(document.createElement("BR"));
}

to use a for loop to loop from 0 to 9.

In it, we create a link with createElement.

Then we call setAttribute to set the eleemnt’s href attribute value.

Next, we set its innerHTML property to the link text.

We then set its onclick property to the click event handler.

We set it to a function that calls onClickLink with i converted to a string.

Then we call appendChild to append the link to a div.

And we call it again to append a br element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *