Home > js_dom_serializer

js_dom_serializer

Js_dom_serializer is a project mainly written in RUBY and JAVASCRIPT, based on the MIT license.

A highly configurable and extremely clean DOM to (X)HTML string serialization

Js Dom Serializer

Serialize live DOM to (X)HTML string.

Usage

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'));

Filters

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']);

Dependencies

None.

Author

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

License

BSD like, see License.txt

Previous:letters