20

jQuery has clean and cleanData methods. What is the purpose of jQuery clean and cleanData methods?

dev.e.loper
  • 35,446
  • 76
  • 161
  • 247

2 Answers2

17

Both are internal, undocumented methods, so you should not use them or rely on their current behavior, because they might change or disappear in the future.

That said, clean() sanitizes the markup in the document fragments that are created from the HTML strings passed to some functions (most notably to $() itself).

cleanData() frees the data associated with elements when they disappear from the DOM, e.g. through remove(), empty(), or html().

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • 1
    Not using them. I was curious because I'm getting errors inside of clean method because of html that was constructed in my own javascript. Hence I'm curious about these methods. – dev.e.loper Aug 16 '11 at 19:49
  • @dev, that might mean your markup is invalid. I'd suggest you double-check it. – Frédéric Hamidi Aug 16 '11 at 19:50
  • Weird because it was working fine in previous version. I just upgraded from 1.4.2. to 1.6.2. I found the problem and fixed it but still confused on why it worked before. – dev.e.loper Aug 16 '11 at 19:51
  • So clean sanitizes markup that was build dynamically using jQuery $()? – dev.e.loper Aug 16 '11 at 19:53
  • @dev, yes, it does. It fixes whitespace and removes `` elements generated by IE browsers, among other things. – Frédéric Hamidi Aug 16 '11 at 19:56
  • Does this unbind events as well? – Hanna Aug 14 '14 at 21:55
  • 1
    @Johannes, I double-checked in 1.11.0 and `cleanData()` is also responsible for cleaning event handlers, yes. Keep in mind, however, this is an internal implementation detail that might have changed thirty-five minutes ago. – Frédéric Hamidi Aug 14 '14 at 22:01
0

From "Secrets of the Javascript Ninja"

<script type="text/javascript">
     function clone() {
       var ret = this.map(function () {
         if (!jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this)) {
           var clone = this.cloneNode(true),
           container = document.createElement("div");
           container.appendChild(clone);
           return jQuery.clean([container.innerHTML])[0];
          }
          else
          return this.cloneNode(true);
          });
          var clone = ret.find("*").andSelf().each(function () {
          if (this[ expando ] !== undefined)
             this[ expando ] = null;
          });
          return ret;
          }
</script>

"... the preceding code uses JQuery's Jquery.clean method, which converts an HTML string into a DOM structure"