In all modern browsers there is a way to get all elements that have a specific class name using Javascript. It’s really useful when manipulating elements on a page. But what if you want to get all elements that start with a certain prefix? Well there’s a way to to do by including this snippet in your Javascript files. It requires Prototype to work.
document.getElementsByPartialClassName = function(value, parentElement) {
var children = ($(parentElement) || document.body).getElementsByTagName('*');
var elements = [], child;
regexp = new RegExp('(?:^|\s)('+value+'.*?)(?:\s|$)');
for (var i = 0, length = children.length; i < length; i++) {
child = children[i];
if (matches = Element.classNames(child).toString().match(regexp)) {
elements.push(Element.extend(child));
}
}
return elements;
};
Now, you can get all of your HTML elements that, for instance, have a class name that begins with ‘comment_’:
var els = document.getElementsByPartialClassName('comment_');
And then do something with them:
for(var i = 0; i < els.length; i++) {
el.style.color = '#F00';
}
I built this function for another project I’ve been working on (which I’ll post about soon). In the project, I was looking for elements that started with a certain prefix, but had different endings (e.g. ‘comment_one’, ‘comment_two’). I used the leftover values to further manipulate the elements. Hopefully this will come in handy for other people as well. Remember you need Prototype for it to work.