Search code examples
alpine-linuxalpine.js

How to get the id using alpine @click


I have this url tag


<a id="day-{{$index+1}}"
  @click="console.log($event.target.getAttribute('id'))"
           <p class="uppercase font-Lato">
              Day {{$index+1}}
           </p>
</a>

but if I click on the url I get "undefined" because it will try to log the child element id, I want to get the "a" element id


Solution

  • Assuming your {{$index+1}} is server side code. You do not need to do a getAttribute() on the $event.target ... You are looking for the .parentNode

    <a id="day-{{$index+1}}"
      @click="console.log($event.target.parentNode.id)"
               <p class="uppercase font-Lato">
                  Day {{$index+1}}
               </p>
    </a>
    

    I find it useful to console.log the entire object and then look at the details of the object in the console to find the "attributes" I'm looking for.