Basic Syntax
With E4X enabled, basic XML elements are valid syntax for variables. For instance
var element = <foo/>;
is perfectly valid in an E4X enabled browser.
Variable declarations are not limited to one element, and as with all JavaScript, can span multiple lines.
var element2 = <foo> <bar/> </foo>;
Additionally, you can specify all of the normal attributes on elements that you would normally include in an XML document.
var element3 = <foo baz="1"/>;
Manipulating Elements
The goal of E4X was to provide an easier way for JavaScript programmers to manipulate an XML document, without going through the DOM interfaces. However, many of the same functions that you would use in the DOM can be used in E4X. The most basic is appendChild
var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2);
which produces exactly the XML document you'd expect
<foo>
<bar/>
</foo>
Javascript Variables
The true power of E4X only begins to come to light, however, when the XML document can interact closely with other JavaScript. With special syntax, we can assign the value of a JavaScript variable to be the value of an E4X element. This is done with brace ({}) notation.
var a = 2; var b = <foo>{a}</foo>;
creates an XML document that reads <foo>2</foo>
.
You can also use brace notation on attributes of elements (their names or values). For example,
var a = 2; var b = 'bar'; var c = <foo {b}={a}>"hi"</foo>;
creates a slightly different XML document: <foo bar="2">"hi"</foo>
.
Note, however, that XML elements can only have text as their value. What really happens with the {} notation is that the variables' toString
method is called, and the returned value is placed in the element. For instance
var a = {foo: 1}; var b = <bar>{a}</bar>;
actually produces a document that reads <bar>[object Object]</bar>
.
Use of inline functions in content
Although the brackets are restricted to single statements for evaluation, one might provide an anonymous function to perform some extra processing inline:
var a = 'foo'; var b = <bar>{function () {var c = a.toUpperCase(); var d = 5 * 5; return c + d;}()}</bar>;
where the above produces: <bar>FOO25</bar>.
See E4X for templating for more discussion on this usage.
Serializing
One of the most powerful tools of E4X is its ability to serialize an entire XML document (or portion thereof) into a string with one simple call to .toXMLString()
var element1 = <foo/>; var element2 = <bar/>; element1.appendChild(element2); element1.toXMLString();
This will print
<foo>
<bar/>
</foo>
Calling toString()
will achieve the same effect in this case, though calling toString()
on an element with only text content will product the text content (e.g., <foo>abc</foo>.toString(); will simply provide 'abc').