Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete the n-th element in a list with javascsript

Tags:

javascript

I know how to delete all elements from a list. I don't know how to delete just one item. Let's say I want to delete the 3th list item

  • of an unorder list . lets say I have the following:
              <ul id="parent">
        <li>
          <label>this is the fist item</label>
        </li>
        <li>
          <label>this is the second item</label>
        </li>
        <li>
           <label>this is the third item</label>
        </li>
        <li>
            <label>this is the fourth item</label>
        </li>
              </ul>
    

    its eassy to delete the fist child or the last child. The list I am building gets built dynamicaly and it will be nice if I can delete the n-th child. It will be nice if I could do something like document.getElementById("someElemet").delete

  • like image 352
    Tono Nam Avatar asked Dec 06 '22 22:12

    Tono Nam


    1 Answers

    var ul = document.getElementById('parent');
    var liToKill = ul.childNodes[2];
    liToKill.parentNode.removeChild( liToKill );
    // or ul.removeChild( ... )
    
    like image 95
    Phrogz Avatar answered Dec 09 '22 10:12

    Phrogz