Home > other >  How to get data attribute of event target in svelte?
How to get data attribute of event target in svelte?

Time:09-28

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 worked.

So appreciate your help.

CodePudding user response:

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;
};

CodePudding user response:

e.target references the thing you just clicked, you'll need to use currentTarget instead and you don't need to do querySelector

EG:

var slug = e.currentTarget.getAttribute("data-url");

I've done a basic example

function goToPage(e){
  console.debug(e.currentTarget.getAttribute('data-url'));
}
<div data-url="https://google.com" class="item" onClick="goToPage(event)">
      <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>
    
    <div data-url="https://google2.com" class="item" onClick="goToPage(event)">
      <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>

  • Related