Search code examples
javascripthtmlweb-applicationsejs

Need to get indexof list item in html using Javascript


In a Todo list web app, i'm using EJS to add items to a <ul> list.

Using javascript i want to be able to retrieve the index of a list item on click to either control its CSS

or delete it in my array of items toDoArray stored in the backend in node.

<ul>
    <% for( var i = 0; i < toDoArray.length ; i++) { %>
    <li class="listItem"> <%= toDoArray[i] %> </li> 
    <% } %>
</ul>

thank you


Solution

  • You can get the parentNode in the click event, then get all its children, then search that list for the one which matches the element that was clicked on (the target of the event).

    addEventListener( 'click', event => {
        const li = event.target;
        if (li.tagName.toLowerCase() !== 'li') return;
        const lis = Array.from(li.parentNode.children);
        const index = lis.indexOf(li);
        console.log(index);
    } );
    <ul>
    <li>item
    <li>item
    <li>item
    <li>item
    </ul>

    That said, you'd probably be better off putting a UID in the data and then including that in a data- attribute, otherwise you are at risk of a race condition deleting the wrong item (e.g. if the user loaded the page in two different tabs).