Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which cases will element.parentElement or element.parentNode be null in a HTML DOM?

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 ?

like image 430
Anurag Vohra Avatar asked Oct 24 '25 01:10

Anurag Vohra


1 Answers

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

like image 179
pilchard Avatar answered Oct 26 '25 14:10

pilchard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!