So in the first part of this small snippet/tutorial i gave you a general concept of targeting classes in a cross browser environment without the need to use a library such as jQuery, in this second and last part i will show you the last few modifications needed to allow for element specific selections and multiple class selections with just a couple of changes. Basically the main two changes in this final part will focus on the wildcard selector and the regular expression in which are the key declarations we need otherwise the prototype won’t work as expected or at all, the first change will need to make is changing document to this:
var ele = document.getElementsByTagName('*')
↓↓↓↓↓↓↓↓↓↓
var ele = this.getElementsByTagName('*')
Next we need to change the regular expression so it looks for multiple classes within the given argument, to accomplish this we simply use the split and join methods like below:
reg = new RegExp(c, 'i')
↓↓↓↓↓↓↓↓↓↓
reg = new RegExp('(' + c.split(' ').join('|') + ')', 'i')
As you can see we first split the string by searching for any spaces and if any are found we then split the string again using a specific pipe separator which allows us to create a word separated expression which is pretty much the most simple way to accomplish this, apart from that you should be able to use the final code below in any browser that doesn’t have native support for getElementsByClassName.
if (typeof document.getElementsByClassName === 'undefined') {
// If the current browser doesn't support the built in class method lets
// create our own to emulate it
Object.prototype.getElementsByClassName = function(c) {
// Collect all the elements in the DOM
var ele = this.getElementsByTagName('*'),
tmp = [],
reg = new RegExp('(' + c.split(' ').join('|') + ')', 'i');
for (var i = 0; i < ele.length; i++) {
// Cache the current element to prevent memory leaks
var e = ele[i];
if (typeof e.className !== 'undefined' && e.className.match(reg)) {
// To improve performance when appending a new array item use the length
// to increment the current index
tmp[tmp.length] = e;
}
}
return tmp;
};
}
I hope you enjoyed this simple snippet/tutorial as i hope to produce more soon!



