How can I add event listener to just button element

Tags: ,



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?

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>


Source: stackoverflow