misohagi
misohagi

Reputation: 23

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?

Upvotes: 1

Views: 1000

Answers (1)

s.kuznetsov
s.kuznetsov

Reputation: 15213

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>

Upvotes: 1

Related Questions