Skip to content

$id

$id is a magic property that can be used to generate an element's ID and ensure that it won't conflict with other IDs of the same name on the same page.

html
<input type="text" :id="$id('text-input')">
<!-- id="text-input-1" -->
 
<input type="text" :id="$id('text-input')">
<!-- id="text-input-2" -->

As you can see, $id takes in a string and spits out an appended suffix that is unique on the page.

Grouping with x-id

There may be cases where you want to maintain the same ID within a scope. For example, you may want to have a <label> element for each input element on the page.

Using just $id alone would generate different IDs for both label and input elements, but you would want to reference the same ID twice (Once in id of input and the other in for of the label).

You could achieve this using x-data directive in conjunction with $id:

html
<div x-data="{ id: $id('text-input') }">
    <label :for="id"> <!-- "text-input-1" -->
    <input type="text" :id="id"> <!-- "text-input-1" -->
</div>
 
<div x-data="{ id: $id('text-input') }">
    <label :for="id"> <!-- "text-input-2" -->
    <input type="text" :id="id"> <!-- "text-input-2" -->
</div>

While this approach is fine, it requires storing the IDs in the component state. To accomplish this same task in a more flexible way, you can use x-id directive in conjunction with $id.

html
<div x-id="['text-input']">
    <label :for="$id('text-input')"> <!-- "text-input-1" -->
    <input type="text" :id="$id('text-input')"> <!-- "text-input-1" -->
</div>
 
<div x-id="['text-input']">
    <label :for="$id('text-input')"> <!-- "text-input-2" -->
    <input type="text" :id="$id('text-input')"> <!-- "text-input-2" -->
</div>

As you can see, x-id accepts an array of ID names. Now any usages of $id() within that scope, will all use the same ID. Think of them as "id groups".

Nesting x-id

You can also nest these x-id groups:

html
<div x-id="['text-input']">
    <label :for="$id('text-input')"> <!-- "text-input-1" -->
    <input type="text" :id="$id('text-input')"> <!-- "text-input-1" -->
 
    <div x-id="['text-input']">
        <label :for="$id('text-input')"> <!-- "text-input-2" -->
        <input type="text" :id="$id('text-input')"> <!-- "text-input-2" -->
    </div>
</div>

Keyed IDs (For Looping)

Sometimes, it is helpful to specify an additional suffix on the end of an ID for the purpose of identifying it within a loop. For this, $id() accepts an optional second parameter that will be added as a suffix on the end of the generated ID.

html
<ul x-id="['list-item']">
    <template x-for="item in items" :key="item.id">
        <li :id="$id('list-item', item.id)">...</li>
    </template>
</ul>