DEV Community

AquaCat
AquaCat

Posted on

【JavaScript】How to embed script in eventhandler

When you want to use a JavaScript for event handler, you can embed the script directly as below.

<div id="element">Hello</div>
<button type="button" onclick="document.querySelector('#element').textContent='Clicked!'">Press Here</button>
Enter fullscreen mode Exit fullscreen mode

As you know, this also works.

<div id="element">Hello</div>
<button type="button" onclick="changeText()'">Press Here</button>
...
<script>
function changeText(){
document.querySelector('#element').textContent='Clicked!'
}
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)