How to get an element’s current onclick method’s contents with JavaScript?

Sometimes, we want to get an element’s current onclick method’s contents with JavaScript.

In this article, we’ll look at how to get an element’s current onclick method’s contents with JavaScript.

How to get an element’s current onclick method’s contents with JavaScript?

To get an element’s current onclick method’s contents with JavaScript, we can use the onclick property.

For instance, we write:

<div>
  hello world
</div>

to add a div.

Then we write:

const div = document.querySelector("div")
div.onclick = () => {
  console.log('hello world')
}
console.log(div.onclick)

to select the div with querySelector.

And then we set div.onclick to a function.

Next, we log the content of div.onclick.

As a result, the console log logs

() => {
  console.log('hello world')
}

Conclusion

To get an element’s current onclick method’s contents with JavaScript, we can use the onclick property.