Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selectors and HTML5 data-* attributes set dynamically

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

like image 906
Tomás Crespo García Avatar asked Dec 26 '12 08:12

Tomás Crespo García


People also ask

How do I use querySelector with data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

How set value to data attribute in jQuery?

The attr() method in jQuery is used to set or return the attributes and values of the selected elements. To set multiple attributes and values: $(selector). attr({attribute:value, attribute:value, ...})

How do you set data attributes in HTML elements?

Creating an HTML Data Attribute Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.

What is data attribute in jQuery?

The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.


1 Answers

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)

like image 128
itsadok Avatar answered Oct 28 '22 07:10

itsadok