Eli Grey

Another E4X DOM library

I just made another E4X DOM library, but this one is intended to implement the optional features in the ECMA-357 standard that are not implemented by Mozilla in JavaScript. The library is named e4x.js due to, for the most part, it only implementing stuff already specified in E4X. The only difference between the standard and my implementation is that the XML.xpath(xpathExpression) method also supports numeric, string, and boolean result types.

E4X DOM toolkit

I have created a small JavaScript toolkit named e4x-dom.js for making it easy to manipulate the DOM with E4X.

The following methods are implemented on XML objects by e4x-dom.js:

Returns the HTML node representation of the XML.
over(element or selector)
Either overwrites element or every element matched by the CSS selector with node().
Same as over(document.getElementById(id)) but also preserves the the id of the element being overwritten in the element replacing it.
fill(element or selector)
Removes every child node of element or every element matched by the CSS selector. Then node() is appended to all of the emptied elements.
Same as fill(document.getElementById(id))
appendTo(element or selector)
Appends node() to element or every element matched by the CSS selector.
Same as appendTo(document.getElementById(id)).
insertBefore(element or selector)
Inserts node() before element or every element matched by the CSS selector.
Same as insertBefore(document.getElementById(id)).
insertAfter(element or selector)
Inserts node() after element or every element matched by the CSS selector.
Same as insertAfter(document.getElementById(id)).

The following are examples of using the toolkit:

var img = <img
 src={prompt("Enter an image URI")}
 alt={prompt("Describe the image")}
<h1>The image was <em>removed</em>.</em>.overId("foobar");
<![CDATA[And then this text node filled the header]]>.fill("#foobar");
// the CDATA isn't itself put into the document but the data inside it is escaped so it
// works in HTML and XHTML
<h1><![CDATA[<html> in here is <escaped>]]></h1>.insertBefore(document.body.firstChild);
// if you just want to create an element quickly, do xml.node()
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"/>.node(); // SVG node
<div/>.node(); // div node
// DOM methods are forwarded to .node()[method]()
<foo bar="baz"/>.getAttribute("bar") === "baz"; // same as getting .@bar
// mass-modifications with CSS selectors
<strong>Absolute links are <em>not</em> allowed</strong>
 .over('a[href^="http://"], a[href^="https://"], a[href^="//"]');
if (user.hasEditPrivileges) {
 // wikipedia-style "put an edit link at the start of each section"
 <a href={"/edit?page=" + page.id}>[edit]</a>.insertAfter('h2');
// <![CDATA[]]> nodes directly accessed are converted to text nodes:
 This is a text node.
 <html> is escaped inside it.