Tim
Tim

Reputation: 13258

Change HTML attribute with 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 can I change the data-filter attribute to true in jQuery? I tried for example:

$('#testlist').attr("data-filter").val(true);

but it does not work.

Anyone an idea?

Best Regards.

Upvotes: 4

Views: 3320

Answers (8)

Bojangles
Bojangles

Reputation: 101473

Try this:

$('#testlist').attr("data-filter", "true");

Or possibly

$('#testlist').attr("data-filter", true);

Upvotes: 2

rsenna
rsenna

Reputation: 11964

So you're using the HTML5 syntax for custom attributes... Nice.

There is a jQuery metadata plugin that allows you to access those attributes in a more semantic way. Just use it like this:

// Reading:
var tooltipTitle = $(".tooltip").metadata().filter;

// Writing:
$(".tooltip").metadata().filter = "whatever";

Upvotes: 1

user113716
user113716

Reputation: 322452

Since you're using jQuery 1.4.4 and "data" attributes, you can use jQuery's .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"

From the docs:

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object.

Upvotes: 6

John Giotta
John Giotta

Reputation: 16934

The correct usage of .attr is .attr(name, value)

So change your code to

$('#testlist').attr("data-filter", true);

http://api.jquery.com/attr/

Upvotes: 1

DKSan
DKSan

Reputation: 4197

Try $('#testlist').attr("data-filter", "true"); instead

Upvotes: 1

wajiw
wajiw

Reputation: 12269

$('#testlist').attr("data-filter",true);

http://api.jquery.com/attr/

Upvotes: 1

James Kovacs
James Kovacs

Reputation: 11651

You're using the wrong syntax. Try this:

$('#testlist').attr("data-filter", true);

Upvotes: 3

Jonathon Bolster
Jonathon Bolster

Reputation: 15961

The syntax for attr is $.attr(attributeName, value);. Try this:

$('#testlist').attr("data-filter", true);

Upvotes: 8

Related Questions