How to add onClick event handler to document.createElement(“th”) with JavaScript?

Sometimes, we want to add onClick event handler to document.createElement(“th”) with JavaScript.

In this article, we’ll look at how to add onClick event handler to document.createElement(“th”) with JavaScript.

How to add onClick event handler to document.createElement(“th”) with JavaScript?

To add onClick event handler to document.createElement(“th”) with JavaScript, we set the onclick property of the th element.

For instance, we write

const newTH = document.createElement("th");
newTH.onclick = () => {
  //...
};

to call createElement with 'th' to create a th element.

Then we set its onclick property to a function that’s called when we click on the th element.

Conclusion

To add onClick event handler to document.createElement(“th”) with JavaScript, we set the onclick property of the th element.