How does the native js determine which node the current node is?

<ul id="ul">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
<script>
    let ul = document.getElementById("ul");
    ul.onclick = (e) => {
        let target = e.target;
        let parent = target.parentNode;
        for(let i = 0; i < parent.children.length; iPP){
            if(target == parent.children[i])
                return i
        }
    }
</script>

now I use the for loop to find the corresponding node and get the location, which is a bit strange. Do you have any other ideas?

Jun.06,2022

you can add an attribute similar to data-index = I to li and get data-index when you click


array.indexOf (target) or string.indexOf (target) ,
is originally used to search for the first index of a given element in an array, or to specify the first occurrence of a string in a string object

here you can borrow the indexOf () method in the native js and use call to point its this to the collection of elements to query.


clickli

var lis = document.querySelectorAll('-sharpul>li');
lis.forEach((el,index) => {
     el.onclick = (e)=> console.log('' + index);

});
Menu