0

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?

1
  • What's with the .find() without a selector? From the documentation: Unlike most of the tree traversal methods, the selector expression is required in a call to .find(). Commented Aug 23, 2016 at 18:11

2 Answers 2

2

The find() method doesn't make any sense in your code just remove that.

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


Use attr() method if you want to reflect the attribute value in HTML code.

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


Refer : jQuery Data vs Attr?

Sign up to request clarification or add additional context in comments.

2 Comments

OK, so how does one correctly use .data() - is this not the use for it?
0

There is no use of .find() , without any selector.

To set any attribute use .attr("attr-name","attr-value"); And to get the attr value use .data("data-status");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.