lunedì, ottobre 29, 2007

[jsn]getElementByClass revisited

Today me and my friends Andr3a had a talk about getElementsByClassName,
I had the idea to write my own implementation since 1 year ago,
in that time I first saw firefox document.evaluate and I blogged to remind myself that I must wrote a better implementation.
The original one was based on Dustin Diaz works.
Seems that the day is come for me, so I've taken my previous work and i've done a lot of optimization, i think now is one of the fastest that you can find around the net
...here the code:


getElementsByClassName.js

/*Kentaromiura 1.0 version*/
document.getElementsByClassName = function(searchClass,tag,node){
var p = function(){
if([].push)return function(a,b){a.push(b)};
return function(a,b){a[a.length]=b}
}();

node = node || document;
tag = tag || '*';

if(document.evaluate){
var xpr = document.evaluate([".//",tag,"[contains(concat(' ',@class,' '),' ",searchClass," ')]"].join(''),node, null, 0, null),
t = true,
els = new Array();
while(t=xpr.iterateNext()){
p(els,t);
}
return els;
}


var els = node.getElementsByTagName(tag),
pattern = new RegExp(["(^|\\s)",searchClass,"(\\s|$)"].join('')),
ce = new Array();

for (var i = 0, max = els.length; i < max; i++) {
if(pattern.test(els[i].className))
p(ce,els[i]);
}
return ce;
}


Tomorrow I will test it more, for now i only can say that it will work on
IE7, FF 2.0.x.x and safari 3.0.3
Teoretically it should work with IE4+, NN 7+,opera 8+ ff 1+ but keep this as not sure
since I can't test it right now.
So if you can leave a comment with your browser I would be grateful.

Ps. since I share my ideas with andr3a, he had wrote his own implementation,
it is very similar to my approach but it's different in some way, so be sure to take a look at his work

bye ;D

Nessun commento: