How do you define an element with an ID attribute using LWC?

Assuming you want to scroll to an element you have access to, you could always use scrollIntoView:

this.template.querySelector("h3").scrollIntoView();

You can basically use any valid CSS selector to find a specific element (e.g. based on a data-id or another attribute).

As far as I can tell, from a lack of documentation, you can't specify an anchor target. You would write the link like this:

<a onclick={handleClick} data-target-id="overview">Overview</a>

Given an H3 like this:

<h3 data-id="overview">Overview</h3>

And scroll with this:

handleClick(event) {
  let targetId = event.target.dataset.targetId;
  let target = this.template.querySelector(`[data-id="${targetId}"]`);
  target.scrollIntoView();
}

((Note: Not tested, you might need to tweak the CSS selector.))

This assumes that the link and target are in the same template, otherwise this won't work. As far as I can tell, you can't target arbitrary elements.


Yes, you can use data-id and the HTMLElement dataset property.

<h3 data-id="overview">Overview</h3>
const element = this.template.querySelector('[data-id="overview"]');
// element.dataset.id === 'overview'