0

I have the following html code.

<ul>
    <li  data-details="li1">first</li>
    <li  >second</li>
</ul>

Notice that for the first element i have add data-details attribute with a value. For the 2nd li element i'm adding the same using jquery. Here is my JavaScript code.

$(document).ready(function()
                  {
                      $("ul li:nth-child(2)").data("details","li2");
                      console.log($("ul li:nth-child(2)").data()); //data can be verified using this
                      alert($("ul li[data-details=li1]").length); //resulting in alert 1
                      alert($("ul li[data-details=li2]").length); //resulting in alert 0
                  });

The data is added we can verify by checking the console. However i'm not able to select the element based on value of data-details which is being added by jquery. Why is it happening so ?

and Here is the jsfiddle link

wh0
  • 279
  • 1
  • 6
  • 22
  • 2
    possible duplicate of [jQuery Data vs Attr?](http://stackoverflow.com/questions/7261619/jquery-data-vs-attr) – Ram May 09 '13 at 04:17
  • http://stackoverflow.com/questions/2891452/jquery-data-selector – Ram May 09 '13 at 04:20

1 Answers1

2

Setting items with .data() does not set attributes. If you set the attribute in the HTML or use something like .attr(), you can use the attribute selector. If you need to find elements that have their .data() set, you need to use .filter():

var el = $("selector").filter(function () {
    return typeof $(this).data("whatever") !== undefined;
});
console.log(el.length);

Note that this isn't the same behavior in the opposite way. When you set an attribute in the HTML or with .attr(), any data-* attribute will automatically be put into .data() by jQuery.

DEMO: http://jsfiddle.net/zTsS4/2/

Note how in the demo, the attribute is set in the HTML for one <li>, and the other is set with .data(). Then the .filter() finds both.

Ian
  • 50,146
  • 13
  • 101
  • 111