arderoma
arderoma

Reputation: 427

Remove elements from the DOM with javascript

I'm getting all the

  • elements from a menu in order to remove the ones I don't want.

    let prodMenu = document.getElementsByClassName("productMenu-category");
    for (let i = 0; i < prodMenu.length; i++) {
        if(i > 0 && prodMenu[i].innerHTML == prodMenu[i-1].innerHTML){prodMenu[i].style.display = "none";}
    }
    

    That's what I have now, but I don't want to hide them I want to remove them. I guess that what I "GET" is something called "collection" that doesn't have any of the function I find for removing it's items. I can't do "delete prodMenu[i]" or "prodMenu.delete()" nor "prodMenu.splice()" because they are not functions from a "collection"

    Upvotes: 1

    Views: 58

  • Answers (1)

    Sergey Sosunov
    Sergey Sosunov

    Reputation: 4600

    Collection is just a collection, it holds the actual DOM nodes found with the selector you gave. Even more - this collection is actually HTMLCollection which is live, it is automatically updated when the underlying document is changed (be careful here). And you dont need to modify it directly, you only need to call a specific remove method of the elements in this collection.

    let prodMenu = document.getElementsByClassName("productMenu-category");
    for (let i = 0; i < prodMenu.length; i++) {
      if (i > 0 && prodMenu[i].innerHTML == prodMenu[i - 1].innerHTML) {
        prodMenu[i].remove();
      }
    }
    

    Upvotes: 1

    Related Questions