0

I have this html:

<input id='myId' type='button' data-this-page='myPage' />

If I want to change myPage to something else, I try this:

$("#viewer_next_page").data('this-page', 'newPage' );

Is this the correct way, because nothing seems to happen. I am making sure the element id created BEFORE the jQuery call as well.

6 Answers 6

2

Try attr

$("#viewer_next_page").attr('data-this-page','newPage');
Sign up to request clarification or add additional context in comments.

1 Comment

Data attributes should be accessed and manipulated via the .data(...) function, not the .attr(...) function...
2

jQuery's .data() method only takes data- attribute values into account once - the first time. When you set it however, it sets actual high-level data on the DOM element. You can even set complex objects and functions using .data(), which you can't with attributes. After that, continue to use the .data() method to extract the value and you'll be fine.

If you insist on using an attribute, use the .attr() method as mentioned in several other answers.

Comments

1

That is the correct way to do it. You'll notice the attribute itself does not change. jQuery manages the data-* attributes internally. On page load, all data-* attributes are read internally into jQuery. Manipulations from then on via the .data(...) method, manipulate the internal object(s). Thus the attribute doesn't appear to change. However, as long as you access the properties in the future like so var page = $('#...').data('this-page');, you'll get the correct values in return.

Comments

1

Have you tried

$("#viewer_next_page").attr('data-this-page', 'newPage' );

2 Comments

Data attributes should be accessed and manipulated via the .data(...) function, not the .attr(...) function...
Nope, I got many times zilch when used data("x")="y" (the value was preserved from before), and what solved problem was: attr("data-x")="y"
1

It is updated. Your HTML is not re-rendering. If you take a look at this:

http://jsfiddle.net/nH9US/

HTML

<input id='myId' type='button' data-this-page='myPage' />

JS

console.log($("#myId").data("this-page"));
$("#myId").data('this-page', 'newPage' );
console.log($("#myId").data("this-page"));

You'll see different outputs each time:

myPage

newPage

Comments

0
$("#viewer_next_page").attr('data-this-page', 'newPage' );

1 Comment

Data attributes should be accessed and manipulated via the .data(...) function, not the .attr(...) function...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.