[SalesForce] querySelector not getting element in lightning web component

I am creating a popover, where I need to position it correctly based on the button's position that triggered it.

It starts like this:

<div id="popoverWrapper" class="popover-wrapper" style={popoverStyle}>
    <section id="popover" class="slds-popover slds-popover_walkthrough slds-popover_large slds-nubbin_left" role="dialog">
        <!--all the insides of the popover-->

I initially just tried a getter on popoverStyle, but when trying to do this.template.querySelector('.popover-wrapper'); it returned null. I thought maybe this was because the getter was happening before actual render.

So I moved the querySelector to the renderedCallback() hook. Putting in a break point, the html is definitely rendered by the time I get to this.template.querySelector('.popover-wrapper'); but it still doesn't find anything.

How might I be able to grab the element in my LWC so I can get its position and dimensions to be able to position properly where I want by finding a space that it will fit?

PS: popoverStyle is getting set to a string that looks like: position: absolute; z-index: 10001; top: ' + correctPositioning.offsetTop + 'px; left: ' + correctPositioning.offsetLeft + 'px;. I am not entirely sure this will even work, but I can't even find the popover element in my JS to try it out.

Best Answer

You probably have an error in your component related with the way that you are trying to set the styles, if you remove style={popoverStyle} the this.template.querySelector('.popover-wrapper') must return you the element and there you can set directly using JS, like:

let popup = this.template.querySelector('.popover-wrapper');
popup.style.position = 'absolute'; 
Related Topic