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

  • I'd like to be able to link to certain portions of my page using URL fragments, eg:

    <h3 id="overview">Overview</h3>
    
    ...
    <a href="#overview">Go to Overview</a>
    

    Unfortunately the IDs i set from within LWC templates get overwritten, so my links don't work. Is there any way to define the ID attribute so it won't change?

  • sfdcfox

    sfdcfox Correct answer

    2 years ago

    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.

    Doesn't work. @tsalb's answer works.

    @MartinLezer It should work... it used to work? It might be worth asking a separate question so this can be reviewed for you. Both their code and mine are virtually identical, just mine is more detailed.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM