Get HTML5 Data Attribute with jQuery

In this tutorial we’ll be taking a look at how to get HTML5 data attribute with jQuery. We’ll create an anchor tag and turn it into a button with  CSS. Then we’ll add two data attributes on it. One for changing it’s size, and an other one to change the background color.

The HTML

<a href="#" class="button" data-name="link" data-size="small" data-color="green">button</a>

The CSS

.button {
    width: auto;
    text-decoration: none;
    border:1px solid #ccc;
    padding: 10px 20px;
    color: #fff;
}

As you can see, we have a class=”button” and 3 data- attributes. A name, a size and color.

We’ll use the data-name to select our button in our jQuery. Then the data-size will determinate the size of the button, and finally the data-color will change the background color of the button.

Let’s get started with the jQuery.

First we’ll create 3 vars, for each data attribute.

To get the value of a data-* attribute we use the .data() jQuery function. When using this function, you need to set the name of your data- attribute in the .data(‘name’).

For example, we have data-size. So in the .data(‘size’) we add size. Also, you need to select the element this attribute is on. I’ve wrote a tutorial about this:  data attribute as selectors in jQuery

var element = $('[data-name="link"]'),
    size = element.data("size"),
    color = element.data("color");
  • Element – We’ll use this as the selector. ()
  • Size – is the size of the button. ( We’ll only accept 2 values, small and large, or empty. )
  • Color – the background color. ( This var accepts any color value. For ex: red, blue, #000, #444 etc… )

Now that we have our variables, with the values of the data attributes, we can start using them.

Let’s create an if / else if statement that will change the buttons size:

if ( size == 'large') {
    element.css('font-size','27px');
} else if ( size == 'small' ) {
    element.css('font-size','10px');
};

This is pretty straightforward, if the value of the data-size  is large,e the font-size is 27px, if the value is small, then it’s 10px;

Now for the color, we’ll only check if it’s empty or not. If it’s empty, do nothing, else set the background color to the color that was given in the value.

if ( color ) {
    $(element).css('background-color', color);
};

And now if we set the following values in our attributes on our button:

<a href="#" class="button" data-name="link" data-size="large" data-color="green">button</a>

Then we should have a big button, with green background color.

And that’s pretty much it. Now that’s up to you how you name your attributes, what value you give to them, and what you do with those values. If you have any questions or suggestion, feel free to leave a comment down below!