Search code examples
javascriptjqueryjquery-data

How to read/write data- attributes after they have been dynamically changed by jQuery?


I am creating a list of items that can be sorted using Mix It Up. I want to have an up and down button on each that increases or decreases the votes for each item and then based on the new votes, moves it up or down in the list.

This is all good and well, but I am running into issues with using data- attributes for Mix It Up. Mix It Up uses the data attributes to sort with, and so in my code I am changing the data-votes attribute (using $(selector).data('votes')). However, whenever I print out the elements with 'changed' data attributes, they are the same as they were at the beginning.

How can I force jQuery / Mix It Up to re-read the data attributes so that Mix It Up can then sort dynamically using the new ones?


Solution

  • I think you'll need to do:

    $(selector).attr('data-votes', newCount);
    

    If you're trying to read the attribute itself. You can chain it if you you want to set things through .data like...

    $(selector).attr('data-votes', newCount).data('votes', newCount);