javascriptsvelte

How to get data attribute of event target in svelte?


I'd like to get the value of data-url in:

  {#each profiles as p}
    <div data-url={p.url} class="item" on:click={goToPage}>
      <div class="row">
        <div class="col s12 l4">
          <div class="a">
             <br />
          </div>
        </div>
        <div class="col s12 l8">
          <p>
            <strong>{p.fn} {p.ln}</strong><br />
            {p.ttl}
          </p>
        </div>
      </div>
      {p.dsc}
       <hr />
    </div>
  {/each}

The function is:

  const goToPage = (e) => {
     var slug = e.target.querySelector("item").getAttribute("url");
    console.log("slug is:", slug);
    window.location.href = slug;
  };

However it does not work and I get

Uncaught TypeError: Cannot read properties of null (reading 'getAttribute')

I have tried other things like

e.target.querySelector("item").getAttribute("data-url");

and

e.target.getAttribute("data-url");

but none of them worked.


Solution

  • The simplest, most straightforward way is to simply pass the slug as an argument to the function instead:

    <div data-url={p.url} class="item" on:click={() => goToPage(p.url)}>
    

    and the function becomes:

    const goToPage = (slug) => {
      console.log("slug is:", slug);
      window.location.href = slug;
    };