Entry
Are XMLList objects live collections like DOM node lists are?
Are XMLList objects live collections like DOM node lists are?
Are E4X XMLList objects live collections like DOM node lists are?
Apr 1st, 2005 01:52
Martin Honnen,
The answer is no, XMLList objects in E4X are not live collections like
the node lists in the DOM are.
Consider the following example (needs Mozilla or other browser
supporting DOMParser and XMLSerializer) to see how a live collection in
the DOM works:
var xmlMarkup = [
'<div>',
' <p>Kibology for all.</p>',
' <p>All for Kibology.</p>',
'</div>'
].join('\r\n');
var divElement = new DOMParser().parseFromString(xmlMarkup,
'application/xml').documentElement;
var paragraphList = divElement.getElementsByTagName('p');
alert(paragraphList.length); // shows 2
// create and append new <p> element
var newParagraph = divElement.ownerDocument.createElement('p');
newParagraph.appendChild(divElement.ownerDocument.createTextNode(
'Kibo is GOD.'));
divElement.appendChild(newParagraph);
alert(paragraphList.length); // shows 3 (!)
alert(new XMLSerializer().serializeToString(divElement));
/* shows three p elements
'<div>
<p>Kibology for all.</p>
<p>All for Kibology.</p>
<p>Kibo is GOD.</p></div>'
*/
As you can see in the above example the DOM collection, the node list
returned by getElementsByTagName, is automatically updated when the
document it is created from changes as after a <p> element is appended
as a child to the <div> element the node list created earlier has a new
updated length value.
Compare that to a corresponding E4X example:
var divElement = <div>
<p>Kibology for all.</p>
<p>All for Kibology.</p>
</div>;
var paragraphList = divElement..p;
alert(paragraphList.length()); // shows 2
// append new <p> element
divElement.p[2] = <p>Kibo is GOD.</p>;
alert(paragraphList.length()); // shows still 2
alert(divElement.toXMLString());
/* shows three p elements
'<div>
<p>Kibology for all.</p>
<p>All for Kibology.</p>
<p>Kibo is GOD.</p>
</div>'
*/
Here you can see that the XMLList object returned from the expression
divElement..p is not automatically updated when a new <p> element is
appended to the <div> element. You would need to recreate the XMLList e.g.
var divElement = <div>
<p>Kibology for all.</p>
<p>All for Kibology.</p>
</div>;
var paragraphList = divElement..p;
alert(paragraphList.length()); // shows 2
// append new <p> element
divElement.p[2] = <p>Kibo is GOD.</p>;
alert(paragraphList.length()); // shows still 2
paragraphList = divElement..p;
alert(paragraphList.length()); // shows 3
That is an important difference between native XMLList objects and DOM
node lists.