Using HTML5 Data Attribute as Selectors in jQuery

When we’re create a jQuery application, most of the time we use CSS Classes or IDs to select specific HTML elements on the page and do things with them. But what happens if we give the application to an other designer who works on the stylings and what not. If he/she changes a few classes and IDs our application is broken, hence we used IDs and Classes as selectors in our jQuery code.

What can we do about this?

With HTML5, they introduced the data-* attribute that can be added to any html element and can store data specific to that element and/or page. These can also be used as selectors in jQuery. And since they have nothing to do with CSS, our designer can freely change classes and IDs around as he/she wants to.

Here’s how this works:

Let’s say we have a button, and a box below that. And we want to make that when the button is clicked, the box disappears and if we click the button again it shows up again.

Our HTML:

<button class="button" data-action="toggle">Click me1</button>
<div class="box" data-action="box">
    I'm a box!
</div>

As you can see above, we have class=”button” and data-action=”toggle” for the button. As for the box, we have class=”box” and data-action=”box”.

And now for the jQuery:

$( '[data-action="toggle"]' ).click(function() {
    $( '[data-action="box"]' ).toggle();
});

And it’s as easy as that. Now we can give our app to the designer and he can change any class or IDs without breaking the application itself. You can use any naming you want, but it must contain data-[your naming here]=”your value here”