Reputation: 1032
I have this problem in my JavaScript class:
//===== i set this data record
jQuery(element).data("types", "row");
console.log(jQuery(element).data("types")); // writes "row" (the element is a div)
//==== into other method
//==== i want find all element with data-types = row
console.log(jQuery("[data-types='row']").length); // writes 0
jQuery("div").each(function(i,e){
console.log(i, jQuery(e).data(), jQuery(e).attr("id")); // writes object{type:row}
});
why with this jQuery("[data-types='row']") i can't find elements ???
Upvotes: 0
Views: 898
Reputation: 272386
When you assign data to an element using jQuery.data()
it does not update the data-*
attribute of the element; you therefore cannot use attribute selectors to select the element.
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).
In order to select these elements you can use the filter()
function with custom function:
jQuery("div").filter(function() {
return $(this).data("types") === "row";
});
Note: If you are also using jQuery UI you would find the :data(key)
selector useful.
Upvotes: 3
Reputation: 782407
The data()
method only uses the DOM when initially reading from an element. When you use it to add or change the data of an element, it puts the data in its internal memory, it doesn't modify the DOM. So DOM selectors won't find it. From the documentation:
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).
To find all the elements, you can use .filter()
:
jQuery("div").filter(function() {
return $(this).data("types") == "row";
});
Upvotes: 1