Is there a way to return all elements with a given classname for use outside a loop with JavaScript?
I mean, even if you use querySelectorAll()
, if you are not in a foreach or an i
loop, it won't do anything.
For example, you can do this:
var test = document.querySelectorAll(".test");
for (var i =0; i < test.length; i++) {
var allClasses = test[i]
// do stuff
}
However, this is less than ideal for more complicated functions, where you don't want to work inside the loop itself. Or you don't want to run loops in loops in loops.
The same goes foreach, you need to work inside the foreach function.
var test = document.querySelectorAll(".test");
[].forEach.call(test, function(t){
var allClasses = t;
// do stuff
});
So is there a simple function to return all classes as a variable for use? Or can you only store it in an array? Either way, how do you do it? Also how would you then use it?