1

I am trying to add HTML5 data-* values with jQuery and nothing seems to be happening, am I doing anything wrong?

Here's my HTML:

<a href="#" data-js="click-chat"></a>

jQuery:

$('[data-js=click-chat]').click(function(){
    $(this).data("role",'test')
})

For some reason it isn't setting any data, or updating the existing value.

4 Answers 4

1

You can use .attr property like this

$(this).attr('id', 'your-id-value');
Sign up to request clarification or add additional context in comments.

Comments

1

Using .data() does not create an attribute, it simply adds data to the element. You should be able to use it using .data('role'), but you will not see an attribute in html.

So if you call .data() on a selector it will check for data- attributes as well as check for data not present in attribute-form.

2 Comments

Thanks! How would I be able to add another value to the data-js attribute? so I get [data-js=click-chat something]
using .attr('data-js', 'some value');
1

You could use the .attr() method if you want to add an attribute to your element. Otherwise all of the other answers are correct with how data() works.

 $('a[data-js="click-chat"').attr('data-monkey', "lemur");

Comments

1

When you use the .data() function jQuery doesn't store the values as actual attributes on the element, so you won't see any changes to the DOM. The first time you call .data() it stores the current values of any data-* attributes on the element(s) internally, then uses that store to get or set values for any subsequent calls.

This isn't consistent with using .attr('data-*') since that does work with the actual attributes defined on the elements, so you want to use one or the other.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.