Created
April 16, 2012 10:56
-
-
Save stereobooster/2397759 to your computer and use it in GitHub Desktop.
getElementsByClassName polyfill
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:true, browser:true, indent:2, maxerr:50 */ | |
(function (document) { | |
"use strict"; | |
function getElementsByClassName(match, tag) { | |
if (document.getElementsByClassName) { | |
return document.getElementsByClassName(match); | |
} | |
var result = [], | |
elements = document.getElementsByTagName(tag || '*'), | |
i, elem; | |
match = " " + match + " "; | |
for (i = 0; i < elements.length; i++) { | |
elem = elements[i]; | |
if ((" " + (elem.className || elem.getAttribute("class")) + " ").indexOf(match) > -1) { | |
result.push(elem); | |
} | |
} | |
return result; | |
} | |
}(document)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:true, browser:true, indent:2, maxerr:50 */ | |
(function (document) { | |
"use strict"; | |
if (document.getElementsByClassName) { | |
document.getElementsByClassName = function (match) { | |
var result = [], | |
elements = document.getElementsByTagName('*'), | |
i, elem; | |
match = " " + match + " "; | |
for (i = 0; i < elements.length; i++) { | |
elem = elements[i]; | |
if ((" " + (elem.className || elem.getAttribute("class")) + " ").indexOf(match) > -1) { | |
result.push(elem); | |
} | |
} | |
return result; | |
}; | |
} | |
}(document)); |
now i get it why there were those spaces
fixed
match = " " + match + " ";
In the polifill.js
Shouldn't the third line be
if (!document.getElementsByClassName) {
instead of
if (document.getElementsByClassName) {
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The updated code still has the problem I described, e.g.
document.getElementsByClassName('oba')
would match elements withclass="foobarbaz"
.