lit-html

How do I clear an element before rendering?


I have inherited an older project using jquery.

I am modernising the code.

In particular this $(selector).html("<h1>lol</h1>"); which as far as I understand is a full replacement of the selectors content.

I always end up with an error if I try to render to a cleared element.

This code:

const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `<h1>TypeScript Starter</h1>`;

// trying to replace jquery $(selector).html("<h1>lol</h1>");

appDiv.innerHTML = '';
render(html`<h1>lol</h1>`, appDiv);

appDiv.innerHTML = '';
render(html`<h1>lol</h1>`, appDiv);

Or see my stackblitz

I always get the following error:

Error in lit-html.js (93:55) Cannot read properties of null (reading 'insertBefore')

Do you know what I am missing? 🧐

Thanks!

Note: This is a duplicate of my question (and based on a suggested technique) from a closed Lit Github Issue

Note: Maybe I am talking rubbish. I can't find a clear answer if render REPLACES content or APPENDS content. A concrete answer on that would be fine!


Solution

  • Lit v1 will clear the container before rendering the first time. Lit v2 will not.

    Only clear the existing container content once before using render. After that render will correctly update content from previous render calls.

    const appDiv: HTMLElement = document.getElementById('app');
    appDiv.innerHTML = `<h1>TypeScript Starter</h1>`;
    
    // trying to replace jquery $(selector).html("<h1>lol</h1>");
    
    appDiv.innerHTML = '';
    render(html`<h1>lol</h1>`, appDiv);
    
    render(html`<h1>lol2</h1>`, appDiv);