Daniel Glazman has added an entry about three ways to emulate getElementsByClass. Of course, there’s another method if your document is xhtml: use xpath like this…

function getElementByClassName(needle) {
var xpathResult = document.evaluate(‘//*[@class = “‘needle'”]’, document, null, 0, null);
var outArray = new Array();
var item;
while (item = xpathResult.iterateNext()) outArray[outArray.length] = item;
return outArray;
}

Code updated to address two minor issues brought to my attention by Biju.

2 Responses to “getElementsByClass: what about dom xpath?”

  1. on 25 Sep 2007 at 15:41john

    minor rev to work in xul:

    getElementByClassName(needle) {
    var xpathResult = window.document.evaluate(‘//*[@class = “‘ + needle + ‘”]’, window.document, null, 0, null);
    var outArray = new Array();
    var item;
    while (item = xpathResult.iterateNext()) outArray[outArray.length] = item;
    return outArray;
    }

  2. on 25 Sep 2007 at 15:44john

    i get it – the blog software is “cleaning” the quotes.

Leave a Reply