lego icon indicating copy to clipboard operation
lego copied to clipboard

this.document refers to the component element when used in Light DOM mode which can be confusing

Open mlbiche opened this issue 7 months ago • 0 comments

Following a documentation discussion, this ticket is opened to discussion and external opinions.

To improve readability, here is the discussion:

@mlbiche: I find the document name confusing. IMHO, it should be this.element instead, as this.document does not correspond at all to document when Shadow DOM is disabled.

@vinyll: it's called this.document as it does refer to the document of the current element. this.document has all the same methods of window.document such as querySelector, children… Indeed when Shadow DOM is disabled it refers to the element itself. Correct me if I'm wrong but it still is a DOM inheritance element as for window.document. If that is not the cas we should rather fix this.document that must refer to the document of the element in case of Light DOM as well.

@mlbiche: Indeed, but this.document.querySelectorAll('a') will only get <a> tags inside the component, while document.querySelectorAll('a') will get all <a> tags within the HTML document. It can lead to confusion, can't it?

@vinyll: calling it this.document is explicitely a document that belong to this. Therefore you may know and expect it to have the behavior of window.document for the current component and not for the window. The purpose of components is to scope the dom, styles… therefore it makes sense to me to access the current component from within the component and not gain access to the upper or lower outside. Accessing the outside document could maybe be reached via window.document? However I would advice never to do that unless some specific documented hacking the system.

@mlbiche: Yes, of course, window.document, or even just document, allows reaching the outside document. For me, it's not such a hacky approach. For example, it is useful to spread a state through the whole application if you don't want to use a store. A good illustration is detailed in Modest JS e-book. But, anyway, I understand your point of view, we will let it as is. 👌

mlbiche avatar Jun 13 '25 08:06 mlbiche