Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get event target without jQuery

I have been trying to get the target (<li> element) from the mouseenter event but so far no luck!

The code:

<ul id="ul">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

<script>
    var ul = document.getElementById('ul');

    ul.onmouseenter = function(e) {
        console.log(e.target);
    };
</script>

Unfortunately the console keeps printing the <ul /> element. Any suggestions?

like image 671
smaili Avatar asked Feb 01 '26 00:02

smaili


1 Answers

It's because the onmouseenter event is not a "bubbling" event, so it only fires when you enter the UL element, not when you enter nested elements, like the LI elements.

Therefore the e.target and the this elements will both be the UL.

If you use onmouseover instead it'll bubble, so you'll get the LI as the e.target when entering the LI elements.

like image 131
user2736012 Avatar answered Feb 02 '26 15:02

user2736012



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!