skip to Main Content

We know both the below codes show the same result, but what are their differences? Can someone explain it? Thank you.

<button @click="$event.target.innerHTML = 'Hello World!'">Replace me with "Hello World!"</button>
<button @click="$el.innerHTML = 'Hello World!'">Replace me with "Hello World!"</button>

2

Answers


  1. From the documentation:

    1. event.target

    a reference to the object onto which the event was dispatched

    i.e. it will return the element that triggered the action, in this case it is the button that you clicked.

    1. $el

    $el is a magic property that can be used to retrieve the current DOM node.

    i.e. it will also select the element that triggered the action.


    They do appear to do the same thing but Alpine provides a more concise reference to the current object.

    Login or Signup to reply.
  2. In your examples it’s the same thing, $el result as a shortcut for $event.target, but you can use $el also outside of an event, for example I have a blade component like this:

    @props(['relOption' => ''])
    
    <div data-rel-option="{{ $relOption }}" x-show="_value==$el.dataset.relOption">
       .....
    </div>
    

    where data-rel-option is set by the backend but is used by Alpine via $el

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search