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);

});
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3adb3-2b9c4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3adb3-2b9c4.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?