2

I have created custom element using LitHTML and my own bloc based library for state management. Now I have stumble upon a case where in a element though pretty inside some other elements, returns null for parentNode and parentElement. I can't figure out why?

enter image description here

What are cases in which parentNode and parentElement be null ?

Anurag Vohra
  • 1,781
  • 12
  • 28
  • 3
    `c` doesn't have a parentElement, but it does have a parentNode which is a shadowRoot. shadowRoots don't have a parentNode property (`c.parentNode.parentNode`) but to access the element that the shadowRoot is attached to you can use `.host` (`c.parentNode.host`). see: [Get shadow root host element](https://stackoverflow.com/questions/25339932/get-shadow-root-host-element), or [ShadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot) – pilchard Nov 28 '20 at 14:28
  • @pilchard yes you are correct, please write it as an answer, I will accept it as solution ot the problem. – Anurag Vohra Nov 28 '20 at 15:11
  • Use **getRootNode** https://developer.mozilla.org/en-US/docs/Web/API/Node/getRootNode . Also see https://stackoverflow.com/questions/54520554/custom-element-getrootnode-closest-function-crossing-multiple-parent-shadowd – Danny '365CSI' Engelman Nov 28 '20 at 20:00
  • @Danny'365CSI'Engelman getRootNode on a normal node will take one directly document node. I traverse through each node and check for propertyat each node as a part of my logic. – Anurag Vohra Nov 29 '20 at 08:33
  • Cool, please add your code so others can learn – Danny '365CSI' Engelman Nov 29 '20 at 12:07

1 Answers1

2

The element c returned by your query has no parentElement, but it does have a parentNode which is a shadowRoot.

ShadowRoots don't have a parentNode property (which is why your c.parentNode.parentNode call returns null) but you can return the element that the shadowRoot is attached by accessing the shadowRoots host property (c.parentNode.host).

See the docs: ShadowRoot

Or related question: Get shadow root host element

pilchard
  • 12,414
  • 5
  • 11
  • 23