Jonathan Wood
Jonathan Wood

Reputation: 67195

Unable to Set Element Attribute Using jQuery data()

I'm having trouble updating elements from JavaScript. My project is fairly complex but here's a tiny piece of it:

myWebService(/*...*/)
.done(function (result) {
    var newRows = $(rows).clone();
    $('#drop-placeholder').after(newRows);
    $(newRows).data('test', 'ZZZZZZZZZZZZZZZZZZZZZZZ');
}

Using Chrome, I can watch these statements execute. However, with newRows in the watch window, I can see that the attribute never gets added/updated. And, sure enough, after the call is done, I don't see the specified attribute on my page.

Can anyone see what I might be missing. rows (and therefore newRows) represents any number of table row elements.

Upvotes: 2

Views: 1109

Answers (2)

jmoerdyk
jmoerdyk

Reputation: 5517

The setting the data via jQuery .data() does not set the attribute, only the underlying data store. If you want to change the attribute, you have to use .attr().

Upvotes: 2

Ken Herbert
Ken Herbert

Reputation: 5236

.data() sets background data that is handled purely by jQuery - it does not set HTML attributes.

If you are trying to set an attribute such as data-test in <div data-test="stuff"></div> you need to use .attr("data-test", variable).

Upvotes: 9

Related Questions