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.