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

2

1 Answer 1

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)

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

2 Comments

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.
Saved a steaming pile of hot mess! :D .data() is really actually useless it seems.

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.