How to JSON.stringify a dom element?

I wondered the same thing, and I appreciate the answer from @ncardeli. In my app, I needed something a little different, and I thought I'd share in case anyone is interested. It recursively displays properties of any children too.

Press the button below to run the example. You can add whatever properties you want to obj and therefore to the result.

function showStringifyResult(target) {
  let result = document.getElementById("result");
  result.select();
  result.setRangeText(JSON.stringify(stringify(target), null, ' '));
}

function stringify(element) {
  let obj = {};
  obj.name = element.localName;
  obj.attributes = [];
  obj.children = [];
  Array.from(element.attributes).forEach(a => {
    obj.attributes.push({ name: a.name, value: a.value });
  });
  Array.from(element.children).forEach(c => {
    obj.children.push(stringify(c));
  });
  
  return obj;
}
#list {
  margin-top: 18px;
}
<h1>
  Press the Stringify button to write the stringified object to the textarea below.
</h1>

<button onClick="showStringifyResult(document.body)" class="c1">
  Stringify
</button>

<div id="list">
  A list for example:
  <ul class="first second">
    <li id="First Item">Item 1</li>
    <li>Item 2</li>
    <li class="inactive">Item 3</li>
    <li data-tag="tag">Item 4</li>
  </ul>
</div>

<textarea id="result" cols="200" rows="20" ></textarea>

Even though this is an old thread here is my addition:

JSON.stringify(target, Object.getOwnPropertyNames(target["__proto__"]), 2)

Give you a quick list for some of the properties of the DOM element.


I think the most reasonable approach would be to whitelist which properties of the DOM element you want to serialize:

JSON.stringify(container, ["id", "className", "tagName"])

The second parameter of the JSON.stringify function allows you to change the behavior of the stringification process. You can specify an array with the list of properties to serialize. More information here: JSON.stringify

If you want to serialize its child nodes too, some extra work is needed. In this case you will have to specify a replacer function as the second parameter of JSON.stringify, instead of an array.

let whitelist = ["id", "tagName", "className", "childNodes"];
function domToObj (domEl) {
    var obj = {};
    for (let i=0; i<whitelist.length; i++) {
        if (domEl[whitelist[i]] instanceof NodeList) {
            obj[whitelist[i]] = Array.from(domEl[whitelist[i]]);
        }
        else {
            obj[whitelist[i]] = domEl[whitelist[i]];
        }
    };
    return obj;
}

JSON.stringify(container, function (name, value) {
    if (name === "") {
        return domToObj(value);
    }
    if (Array.isArray(this)) {
        if (typeof value === "object") {
            return domToObj(value);
        }
        return value;
    }
    if (whitelist.find(x => (x === name)))
        return value;
})

The replacer function transforms the hosted objects in childNodes to native objects, that JSON.stringify knows how to serialize. The whitelist array has the list of properties to serialize. You can add your own properties here.

Some extra work in the replacer function might be needed if you want to serialize other properties that reference hosted objects (for example, firstChild).

Tags:

Javascript

Dom