title: How to serialize DOM node to JSON even if there are circular references?
body: <p>I want to serialize DOM node or even whole <code>window</code> to JSON.</p>
  
  <p>For example:</p>
  
  <pre><code> &gt;&gt; serialize(document)
      -&gt; {
        "URL": "http://stackoverflow.com/posts/2303713",
        "body": {
          "aLink": "",
          "attributes": [
            "getNamedItem": "function getNamedItem() { [native code] }",
            ...
          ],
          ...
          "ownerDocument": "#" // recursive link here
        },
        ...
      }
  </code></pre>
  
  <h2>JSON.stringify()</h2>
  
  <pre><code>JSON.stringify(window) // TypeError: Converting circular structure to JSON
  </code></pre>
  
  <p>The problem is JSON does not support circular references by default.</p>
  
  <pre><code>var obj = {}
  obj.me = obj
  JSON.stringify(obj) // TypeError: Converting circular structure to JSON
  </code></pre>
  
  <p><code>window</code> and DOM nodes have many of them. <code>window === window.window</code> as will as <code>document.body.ownerDocument === document</code>.</p>
  
  <p>Also, <code>JSON.stringify</code> does not serialize functions, so this is not what I'm looking for.</p>
  
  <h2><a href="http://www.sitepen.com/blog/2008/06/17/json-referencing-in-dojo" rel="noreferrer">dojox.json.ref</a></h2>
  
  <pre><code> `dojox.json.ref.toJson()` can easily serialize object with circular references:
  
      var obj = {}
      obj.me = obj
      dojox.json.ref.toJson(obj); // {"me":{"$ref":"#"}}
  </code></pre>
  
  <p>Good, isn't it?</p>
  
  <pre><code> dojox.json.ref.toJson(window) // Error: Can't serialize DOM nodes
  </code></pre>
  
  <p>Well not good enough for me.</p>
  
  <h2>Why?</h2>
  
  <p>I'm trying to make DOM compatibility table for different browsers. For instance, Webkit supports placeholder attribute and Opera doesn't, IE 8 supports <code>localStorage</code> and IE 7 doesn't, and so on.</p>
  
  <p>I don't want to make thousands of test-cases. I want to make generic way for test them all.</p>
  
  <h2>Update, June 2013</h2>
  
  <p>I made a prototype <strong><a href="https://github.com/NV/dom-dom-dom.com" rel="noreferrer">NV/dom-dom-dom.com</a></strong>.</p>