Skip to content

[lit-html] get ParentNode should handle when parentNode is null #3611

@JamieKook

Description

@JamieKook

Which package(s) are affected?

Lit Core (lit / lit-html / lit-element / reactive-element)

Description

I recently had an issue with how I was working with a lit component. In attempting to debug my problem, I encountered this.
In the _$setValue method in lit-html.ts, there is an error thrown when this.parentNode === null

_$setValue(value: unknown, directiveParent: DirectiveParent = this): void {
    if (DEV_MODE && this.parentNode === null) {
      throw new Error(
        `This \`ChildPart\` has no \`parentNode\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \`innerHTML\` or \`textContent\` can do this.`
      );
    } 

However, I was not seeing this useful error because in get ParentNode() in the same file, the first if statement checks the nodeType of the parentNode which fails because the parentNode is null and I got a less helpful error. It seems that if we can have this.parentNode === null, a null value for the parentNode should be handled in the get ParentNode method.

get parentNode(): Node {
    let parentNode: Node = wrap(this._$startNode).parentNode!;
    const parent = this._$parent;
    if (
      parent !== undefined &&
      parentNode.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */
    ) { 

Reproduction

  1. Create a lit component that will exit and reenter the document
  2. Have that lit component render a second lit component in the template
  3. Foolishly change the innerText of the parent lit component to remove the child in the Updated method
  4. Debug

Workaround

I have not found a workaround

Is this a regression?

No or unsure. This never worked, or I haven't tried before.

Affected versions

2.6.1

Browser/OS/Node environment

Browser: Chrome 109.0.5414.87
macOS Ventura 13.1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    ✅ Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions