how to get reference to the element hidden in lwc?

1.5k views Asked by At

I am learning lwc and I came across this problem. I have the following code.

html:

<template if:true={showLayout}>
   <template if:true={showAllTabs}>
      <div class="tab-container">
         <div class="left-arrow">
             'Left icon code'         
         </div>
         <ul class="slds-tabs_default_nav tab-list">
            'li elements to disply the tabs'
         </ul>
         <div class="right-arrow">
             'Left icon code'         
         </div>
      </div>
   </template>
</template>

I am trying to get the reference of the ul element and right-arrow div in javascript to decide whether right navigation arrow should be shown or not based on scroll available on ul element. But, I am unable to get the reference of these 2 elements. I know that they are hidden thats why I am not able to find the reference. But, how to overcome this issue. I tried to get the reference in renderedCallback() and in the function where showAlltabs becomes true, nothing worked.

JS:

renderedCallback(){
   let tabList = this.template.querySelector('.tab-list');
   let rightArrow = this.template.querySelector('.right-arrow');
}

handleLayoutOpen(){
   this. showAllTabs = true;
   let tabList = this.template.querySelector('.tab-list');
   let rightArrow = this.template.querySelector('.right-arrow');

}

In both function I get undefined for both the elements.

Went through this developer guide https://lwc.dev/guide/html_templates#render-html-conditionally , nothing is mentioned about template reference here.

PS: I am very new to LWC, please be kind in your answer.

1

There are 1 answers

0
LoneWolf On

I was able to find a alternate solution to this problem. I used slds-hideand slds-show classes, instead of if:true.

<div class='slds-hide'>
   <div class='slds-hide'>
      <div class="tab-container">
         <div class="left-arrow">
             'Left icon code'         
         </div>
         <ul class="slds-tabs_default_nav tab-list">
            'li elements to disply the tabs'
         </ul>
         <div class="right-arrow">
             'Left icon code'         
         </div>
      </div>
   </div>
</div>

In JS I used Element.classList.add() and Element.classList.remove() methods to show and hide the divs whenever I need.

NOw I am able to get the reference of the hidden elements as they are not truly absent in the dom.