Example: XML using strings / innerHTML
// Short, but notice how I forgot to close the paragraph // Also, this is non-standard, and only works in HTML myElement.innerHTML = '<p><b>Hello</b> <i>World</i>';
Example: XML using the DOM
// That must be one of the longest hello world // examples I've ever written var paragraph = document.createElement('p'); var bold = document.createElement('b'); var hello = document.createTextNode('Hello'); bold.appendChild(hello); var italic = document.createElement('i'); var world = document.createTextNode('World'); italic.appendChild(world); var space = document.createTextNode(' '); paragraph.appendChild(bold); paragraph.appendChild(space); paragraph.appendChild(world); myElement.appendhChild(paragraph);
As it happens, I am working on something that requires quite a lot of DOM manipulation within the browser, and tired of constructing XML using the DOM API I set to give the new E4X capabilities of Firefox 1.5 a try. The dissapointing reality, I soon found out, is that while E4X is very much present, it can’t be used for accessing or creating DOM elements. So if you plan on parsing some XML data, or generating XML from your program you can use E4X, but DOM manipulation, arguably the most important activity involving XML in a browser is not served by this new extension at all.
Example: How E4X could be used with the DOM
// This is structured XML, notice how there are no quotes var p_xml = <p><b>Hello</b> <i>World</i><p>; // But unfortunately you can't do that var p_element = document.createElement(p_xml); myElement.appendChild(p_element)
Why doesn’t Firefox provide a way to construct and manipulate DOM elements using E4X? It’s hard to blame the mozilla developers, given that the ECMA standard does not include any mention of the DOM or how to interact with it. Any extension they would have come up with would end being the next generation innerHTML non-standard.