14

I have this working:

  <div data-people="australian">Australian people eats...</div>

  <script type="text/javascript">
    alert($("[data-people=australian]").html());
  </script>

But this other doesn't work and I don't know how to solve:

  <div id="mich">Australian people eats...</div>

  <script type="text/javascript">
    $("#mich").data("people", "australian");

    alert($("[data-people=australian]").html());
  </script>

Why I can't set the data-* HTML5 attributes from jQuery and the use them to select a DOM object???

Lot of thanks

  • Is your question "why" or "how to solve"? Maybe look at http://stackoverflow.com/questions/13094777/find-elements-by-custom-data-attribute-value/13094850#13094850. – pimvdb Dec 26 '12 at 08:44
  • possible duplicate of [Why don't changes to jQuery $.fn.data() update the corresponding html 5 data-\* attributes?](http://stackoverflow.com/questions/5507718/why-dont-changes-to-jquery-fn-data-update-the-corresponding-html-5-data-a) – itsadok Dec 26 '12 at 08:48

1 Answers1

37

The data- attribute to jQuery data() mapping is one-direction. You should use the attr() function if you want to actually set the attribute on the node.

$("#mich").attr("data-people", "australian");

From the docs:

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

itsadok
  • 28,822
  • 30
  • 126
  • 171
  • 2
    It's pretty insane that jQuery's own selector for data doesn't take this in to account and checks its data cache. Makes `.data()` less useful and the source of hard to track down bugs. – Vala Sep 19 '16 at 13:24
  • Saved a steaming pile of hot mess! :D `.data()` is really actually useless it seems. – Romeo Sierra Mar 19 '18 at 05:37