Know Your Tools: jQuery and HTML5 Data Attributes

Image for Know Your Tools: jQuery and HTML5 Data Attributes

jQuery is a defacto standard for most web applications like it or not. Most jQuery examples that manipulate the DOM use CSS classes as selectors. In small examples, this is perfectly fine, but what happens as you move on and off new developers and designers on to the project. A designer must be knowledgable on what CSS classes are being used in the JavaScript and a developer must know how a class name is being used within the DOM. It becomes very difficult to maintain.

At Intuitive Company, we’ve introduced a standard way in which we decouple the design assets from the JavaScript. Rather than hooking onto DOM elements via CSS classes, we are using HTML5 data attributes.

For example, if I have a button in the markup:

Code Pen Example

Rather than writing a typical jQuery selector $(’.ic-button’), our practice is to select based off the data attribute as so $(’[data-ic-class=“button”]). You can view the code at CodePen.

By following this practice, a designer can make changes to the class name without worrying about the way the JavaScript is hooking on to the element.

One might jump to the conclusion that this approach is only supported on HTML5 browsers since it utilizes the data-* attributes introduced in HTML5. Fortunately this is not the case. In older browsers, the data-* attributes are treated as custom attributes and supported. There is one downside that hopefully isn’t a problem for you. If you have to support IE6 (see The Internet Explorer 6 Countdown immediately!), then you may run into performance issues due to reference the data-* attributes as opposed to class names.

We’ve used this practice over the last year and have been very pleased with the results. We are able to make design modifications without fear that they’ll break our JavaScript and vice versa.

About the Author

Image of Bob Rullo