Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the data stored with jquery's data method removed when the element is removed?

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.

like image 632
toofamousname Avatar asked Dec 04 '10 11:12

toofamousname


People also ask

How to remove data using jQuery?

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.

How to remove value from data attribute in jQuery?

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.

How do you check if data attribute exists in jQuery?

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 .


1 Answers

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:

  • Here's where it happens for .remove()
  • Here's where it happens for .empty()
  • Here's where it happens for .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.

like image 176
Nick Craver Avatar answered Oct 22 '22 05:10

Nick Craver