Capure js click button over another button

I have a button over another button in a way like this

<button id="button1" style="width:200px; height:200px; position:relative; border: 1px solid;">

    <a href="#" id="button2" style="position: absolute; border:1px solid;">test</a>
</button>

<script>

    document.getElementById("button1").onclick = function(e) {  
        console.log("button1 click");
    }

    document.getElementById("button2").onclick = function(e) {  
        console.log("button2 click");
    }

</script>

When I click on button2, also the button1 is clicked, but I would only capture button2 click

Tried with e.preventDefault() without success…

Answer

First of all, I think it’s not valid HTML. You shouldn’t have a <a> tag inside <button>

For more information about <button> check this.

You’re facing this problem because of event bubbling. Check this links for more details regarding event bubbling. https://javascript.info/bubbling-and-capturing

You can fix this problem using event.stopPropagation(); But I must say it’s not the right approach