Keith Devens .com |
Saturday, May 17, 2008 | ![]() |
| I meant what I said, and I said what I meant. An elephant's faithful, one hundred percent! – Horton (Horton Hears a Who, Dr. Seuss) | ||
|
| ← Guides | World of Warcraft Pro | Windows PowerShell → |

Revence (http://freeshells.ch/~revence) wrote:
Revence (http://freeshells.ch/~revence) wrote:
Okay, I'm back with the code. I saw one John Resig wrote, and it is here.
My own is here. Frankly, I wonder why that one of Dustin Diaz gets mentioned at all. It looks horrible to me, especially that j++. Eeewww. Also, Array.length is O(1), so why clutter with a var for a var? Then the repeated checking if "equals null". This was a Java programmer, I can bet. And when will people learn that regular expressions are not to be used where simple comparisons would work?
(I didn't use regexen in mine, because I've never needed 'em. I see that many versions have them in there, but ... isn't this an example of people forgetting that YAGNI?)
function getElementsByClass(cls, node, tag)
{
if(document.getElementsByClass)
return document.getElementsByClass(cls, node, tag);
if(! node) node = document;
if(! tag) tag = '*';
var them = node.getElementsByTagName(tag),
rez = [];
for(var notI = 0; notI < them.length; ++notI)
if(them[notI].className == cls) rez.push(them[notI]);
return rez;
}
When I still coded JavaScript, this function worked for me. (It should work, though not tested ... so it shouldn't.
)
Feel free to post a comment below. Please see my comment policy.
Formatting Rules (No HTML):
Generated in about 0.177s.
(Used 8 db queries)
That getElementsByClass is severely flawed, I think. It uses a regular expression (which may run you into, at the very least, O(n log(n)) comparisons). That bites rather hard, if you have many elements - as you will.
A simple comparison would suffice, I think. But that's not the real sin, here.
The real sin is not checking if getElementsByClass is already implemented. So, if you drop this in, you're in trouble. Say, Safari Webkit has one in-built, these days. You'd, in this case, override a native implementation (which is, of course, faster and more-correct) for this one.
Plus, that code is horribly very non-JavaScript. That guy is probably a Java or C/C++ programmer, originally. I'll be back with code, if it suits you. (I'll write it, anyway, and check back to see if posting it would still be pertinent.) There is a stunningly-good implementation I saw for one of the libs. Prototype, I think.