Search code examples
javascripttypescriptconstructorlit

Getting tag based on ID of element inside shadowroot


I am having the below html that I render in a lit component:

render() {
    return html`
          <div class="table">
            <div id="col">
              <p>testing this component</p>
</div>
</div>`

through the below constructor I'm calling a resize handler:

constructor() {
    super();
    window.addEventListener('resize', this._handleResize);
  }

the handleresize method is as below:

private _handleResize = () =>{
  var some_id = document.getElementById('col');
  var tag = some_id.tagName; ///some_id is coming out as null
}

I am trying to get the tag of 'col' ID and it's throwing me null. Can someone tell what is the mistake here?


Solution

  • Instead of querying for the element, you should use a reference:

    Referencing rendered DOM

    import {ref} from 'lit/directives/ref.js';
    
    [...]
    
      colRef = createRef();
    
    [...]
    
      render() {
        return html`
          <div class="table">
            <div id="col" ${ref(this.colRef)}>
              <p>testing this component</p>
            </div>
          </div>`
      }
    
      private _handleResize = () =>{
        const col = this.colRef.value!;
        const tag = col.tagName;
      }
    
    

    I also suggest to using const and let instead of var. Furthermore you should probably use ResizeObserver instead of an eventlistener on window. Also don't forget to unregister your eventlisteners.