Assuming the relevant class is always the only class on those elements, you can do it with an "attribute starts with" selector combined with Array#map
:
var list = document.querySelectorAll("div[class^=userName_]");
var classArr = Array.prototype.map.call(list, function(div) {
return div.className;
});
Matt Burland points out that that will return an array with duplicate entries if there are multiple elements with the same class. Two ways to address that:
Array#reduce
, but this use of it isn't very efficient:
var list = document.querySelectorAll("div[class^=userName_]");
var classArr = Array.prototype.reduce.call(list, function(array, div) {
if (array.indexOf(div.className) === -1) {
array.push(div.className);
};
return array;
}, []);
...or using a temporary map:
var list = document.querySelectorAll("div[class^=userName_]");
var map = {};
Array.prototype.forEach.call(list, function(div) {
map[div.className] = true;
});
var classArr = Object.keys(map);
Array#map
, Array#reduce
, Array#forEach
, and Object.keys
are all ES5 features, but if you need to support older engines, they can all be shimmed.
querySelectorAll
is available on all modern browsers, and IE8.