Created: 2008-12-21 14:01
Updated: 2016-05-08 20:10
License: mit


Js Dom Serializer

Serialize live DOM to (X)HTML string.


Create a serializer object, then use its serialize or its content method passing a DOM node as argument.

new JsDomSerializer().serialize(document.getElementById('some-element'));


You can disallow the serialization of any node through a filtering function. The function is called with the node as its only argument, except for attribute nodes where it receives the node containing the attribute and the attribute name. If the function returns false, node is skipped.

var serializer = new JsDomSerializer();
// disallow serialization of /script elements
serializer.addFilter(function(node) {
  if (node.nodeType == 1 && node.tagName.toLowerCase() == 'script') {
    return false;
// disallow serialization of @name attributes for /form elements
serializer.addFilter(function(node, attrName) {
  if (attrName == 'name' && node.tagName.toLowerCase() == 'form') {
    return false;

Translation of node names

Use the translation method to specify element translations.

var serializer = new JsDomSerializer();
// translate /b elements as /strong
serializer.translation('b', 'strong');
// do not output tags for /div elements
// but process its content
serializer.translation('div', '');
// skip /iframe elements
serializer.translation('iframe', false);

Exportable attributes

Only attributes in white lists are serialized (this is due to a defect in Internet Explorer and its handling of nodeElement.attributes collections). Modify the default list (JsDomSerializer.attrs['*']) before instantiating the serializer.

Configure exportable attributes by node name using the allowedAttributes method:

var serializer = new JsDomSerializer();
// serialize just the `href` attribute for /a elements 
serializer.allowedAttributes('a', ['href']);




Choan Gálvez http://choangalvez.nom.es/


BSD like, see License.txt

Cookies help us deliver our services. By using our services, you agree to our use of cookies Learn more