Skip to content
Advertisement

Lit-html target a DOM node

Imagine I have a template with a button and a spinner next to it. How can I tell the spinner to show up when the button is pressed?

return `html
  <button @click=${handleClick}>Press</button>
  <div class="spinner"></div>
`

I want to be able in ‘handleClick’ to target this specific spinner and not some other in the page (there might be many we don’t know). In react we can use refs.

Advertisement

Answer

This really depends on how you’re rendering the other spinners and where they are. In the template you provided you could use a binding like the following (also, I don’t know how this spinner activates so I’ll assume it uses an active class):

import {render, html} from 'lit-html';

const spinnerActive = false;

const handleClick = () => {
  spinnerActive = true;
  renderTemplate();
}

const template = html`
  <button @click=${handleClick}>Press</button>
  <div class="spinner ${spinnerActive ? 'active' : ''}"></div>
`;

const renderTemplate = () => {
  render(template, <Host DOM node>);
};
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement