user1486133 user1486133 - 3 months ago 12
jQuery Question

Using .data to add data attribute using jQuery

I have two spans on my site:

<span class="view-toggle"></span>


And I'd like to firstly set
data-status="inactive"
(to clear it of any settings), and then add
data-status="active"
to one element.

I have the following:

$('.view-toggle').find().data("status","inactive");
$(button).data( "status", "active");


I can confirm that
$(button)
correctly identifies the one span that I want to add
active
to.

I'm not getting any console errors, but I'm also not getting the addition of any data attributes.

Am I using
data()
incorrectly?

Answer

to get the value of your attribute :

<strong id="the_id" data-original-title="I NEED THIS">

$('#the_id').data('original-title');

to set the value of your attribute

$('#div').attr(attname,attvalue);