Reputation: 21
I'm very beginner so I'm sorry if something doesn't make sense :)
I'm trying to search an XML DOM by ClassName, using a custom function which only seems to work when I'm searching the document the script is in.
This is the function:
Object.prototype.getElementsByClassName = function(getElementsByClass) {
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","somexml.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var foo = xmlDoc.getElementsByClassName("gridCellAlt");
(I then output foo somewhere down later - the output all works fine.)
Now, everything works if I use xmlDoc.getElementsByTagName
and use a tag name - however, the page I am going to be accessing makes use of class names, so I want to use xmlDoc.getElementsByClassName
. The above script works completely fine if I use var foo = document.getElementsByClassName("gridCellAlt");
and include the information I am accessing in the page running the script, but when I try to use it on the xmlDoc DOM it doesn't work. To sum it up: the only time the script doesn't work is when I'm using the xmlDoc (instead of document), and the getElementsbyClassName
in conjunction. If I use document and getElementsByClassName its fine. If I use xmlDoc and get elementsByTagName
its fine.
I'm thinking the getElementsByClassName
isn't searching within the DOM nodes correctly, but even if I put class="gridCellAlt"
somewhere in the root node of a test DOM it still doesn't find it. I've tried adding more information behind foo = xmlDoc.getElementsByClassName("gridCellAlt", (info here))
but that doesn't seem to address the issue either.
Upvotes: 2
Views: 299
Reputation: 15338
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
xmlDoc=xmlhttp.responseXML;
var foo = xmlDoc.getElementsByClassName("gridCellAlt");
}
}
Upvotes: 2