jedierikb
jedierikb

Reputation: 13079

How to update the data-* attrs?

Using jQuery 1.7.2, how do I update the data-* attrs in my elements when the data model is updated?

For example:

$('el').attr('data-x', 400);
var data = $('el').data( );
data.x += 100;

Changing the $(el).data() does not seem to push the changes back to the elements' data-* attrs.

Why would I want this? I would like to use the built in jQuery selectors with up-to-date data .

Upvotes: 0

Views: 710

Answers (3)

zzzzBov
zzzzBov

Reputation: 179046

There's no reason to push data back onto the element's attribute unless you're going to be working directly with the attribute values (such as in a non-jQuery plugin). The changes only happen client-side, so it's much more performant to simply cache the values retrieved from the [data-*] attributes.

If you absolutely must update the attribute value, you should use the .attr() method.

Additionally, when retrieving data, it's important to know that the .data() method will try to figure out what sort of data type your content is:

<div data-foo="bar" data-baz="0" data-fizz='{"a":"b"}' data-bool="true"></div>

$('div').data('foo');       //returns "bar"
$('div').attr('data-foo');  //returns "bar"

$('div').data('baz');       //returns 0
$('div').attr('data-baz');  //returns "0"

$('div').data('fizz');      //returns {"a":"b"} as an object
$('div').attr('data-fizz'); //returns "{\"a\":\"b\"}"

$('div').data('bool');      //returns true
$('div').attr('data-bool'); //returns "true"

Upvotes: 2

Lee
Lee

Reputation: 13542

To work with data-* attributes, use the attr(name,value) method -- same as any other attribute value:

To set it:

$('#myDiv').attr('data-name', 'bob');

To get it:

var name = $('#myDiv').attr('data-name');

The difference between data-* attributes, and the $(..).data() function, is that the attributes can contain only string values, while jQuery's data() function allows you to attach (and later retrieve) actual javascript objects.

var obj = { 
  name: bob, age: 27,
  foo: function() { ... }
};
$('#myDiv').data('some.identifier', obj);

// then later
var obj2 = $('#myDiv').data('some.identifier');

console.log(obj2 === obj);  // true!

Upvotes: 1

Zendy
Zendy

Reputation: 1684

You can do it like this:

$('el').attr('data-x', 400);

Upvotes: 4

Related Questions