What happens to the data stored for a given element using the jQuery.data() function after that element is removed or replaced? In tests it appears this data is no longer available after the element it was attached to is removed.
To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.
removeData() method allows us to remove values that were previously set using . data() . When called with the name of a key, . removeData() deletes that particular value.
The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .
Yes, when an element is removed by .remove()
or .empty()
on a parent (or .html()
on a parent), the data (stored in the jQuery.cache
object) is cleaned up as well.
You can see in the source:
.remove()
.empty()
.html()
In all these cases, the jQuery.cleanData()
function does the work.
In case others finding this are looking for ways to directly remove data, there are functions for this, just not commonly used directly: .removeData()
and $.removeData()
. They behave like .data()
and $.data()
in usage - without the data key (name parameter) they'll clear all data values for the element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With