Change HTML attribute using jQuery
I am using jQuery 1.4.4. and I have this source code:
<div id="area1"> <ul id="testlist" data-filter="false"> </ul> </div> How to change data filter attribute to true in jQuery? I tried for example:
$('#testlist').attr("data-filter").val(true); but that will not work.
Any idea?
Best wishes.
+4
8 answers
Since you are using jQuery 1.4.4 and "data" attributes, you can use the jQuery .data() method :
Example: http://jsfiddle.net/patrick_dw/SLskn/
alert( $('#testlist').data("filter") ); // alerts "false" $('#testlist').data("filter",true); alert( $('#testlist').data("filter") ); // alerts "true" Like jQuery 1.4.3 HTML 5, data attributes will be automatically pulled into the jQuery data object.
+6
So you are using HTML5 syntax for custom attributes ... Nice.
There is a jQuery metadata plugin that allows you to access these attributes in a more semantic way. Just use it like this:
// Reading: var tooltipTitle = $(".tooltip").metadata().filter; // Writing: $(".tooltip").metadata().filter = "whatever"; +1