lit-element

Add and remove active class


I have a navbar contains some items. How to add an active class to the clicked item and remove from other items? i have tried to get those elements by document.getElementsByClassName but it throws error


Solution

  • Since you are talking about LitElement and webcomponents most likely the component you are working on has a Shadow DOM.

    So because of that querying the document is from the start a mistake, you want the lookup to happen inside your element, not in the top document level.

    So inside one of your component, to get all the elements with a certain class instead of:

    document.getElementsByClassName('item')
    

    you would do something like

    this.shadowRoot.getElementsByClassName('item')
    

    or

    this.shadowRoot.querySelectorAll('.item')