Recent Changes - Search:

E4X & DOM

For now, I mostly want to use E4X as a quick way of writing HTML in javascript. This function lets me do that (modified from here):

/// Convert e4xNode to a DOM node
/// e.g. e4d(<textarea cols="20">Some text</textarea>);
///    --creates textarea dom node
function e4d(e4xNode) {
	var me = e4d;

	/// Setup static values
	if (!me.Const) {
		me.Const = { mimeType: 'text/xml' };
		me.Static = {};
		me.Static.parser = new DOMParser();
	}

	/// Convert the e4x node to a dom node
	var xhtml = <testing xmlns="http://www.w3.org/1999/xhtml" />;
	xhtml.test = e4xNode;
	var domTree = me.Static.parser.parseFromString( xhtml.toXMLString(),
		me.Const.mimeType );
	var importMe = domTree.documentElement.firstChild;

	/// Find the first element (rather than whitespace, for example)
	while (importMe && importMe.nodeType != Node.ELEMENT_NODE) {
		importMe = importMe.nextSibling;
	}

	/// Import the node into window.document, and return it
	return importMe ? document.importNode(importMe,true) : null;
}

/// Convert DOM node to e4xNode
/// Note: All tags will be uppercase, and matching is case-sensitive
/// e.g. d4e(document.body)..A.@name
///    -- grabs all named anchors (as e4x list)
function d4e(domNode) {
	var xmls = new XMLSerializer();
	return new XML(xmls.serializeToString(domNode));
}

The second function (d4e) converts back. Here are examples of using the above functions:

/// Add an input element to the page
document.appendChild(e4d(<input type="text" />));

/// Find every table element in the page, return as e4x nodelist
d4e(document.body)..TABLE

In case it isn't clear, d4e does not return a live tree. Any changes you make to it won't occur in the document. I'm thinking of writing some functions to allow that, but then again it might be better to just wait for Mozilla's E4X-DOM integration.

Page last modified on January 26, 2007, at 05:17 PM
View Edit History Print Recent Changes Search