0

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 ???

2 Answers 2

3

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.

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

Comments

1

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";
});

Comments

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.