Skip to content
Advertisement

How can I add event listener to just button element

Here is my code.

<button id ="id"><span>fire!</span></button>
<script>
document.getElementById('id').addEventListener('click',e=>{
    console.log(e.target)
}) 
</script>

then we can find simple button in DOM. Once I click button, script returns

<span>fire<span> 

or

<button id="id"> ...</button>

.

How can I add event listener to just button element?

Advertisement

Answer

This is as one of the options… You can use the currentTarget.

In your case, it will be like this:

document.getElementById('id').addEventListener('click', e=> {
    console.log(e.currentTarget);
});
<button id ="id"><span>fire!</span></button>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement