I need to get a group of elements by class name, e.g. class_a , class_b etc.
Is there a standard way of doing this? Basically i have a bunch of containers that need to be displayed on screen when a button is clicked. I woulda thought this a very easy task since ive been doing this with single containers with a single ID using getElementById() for years.
I tried using getElementsByClassName() but for some reason im having difficulty getting it to work e.g. iterating over the object.
Im not a programming noob, this is just an area of JS im unfamiliar with.
There is no magic with the iterating. What the class handling functions do well is to accurately check and set class names.
var divs = document.getElementsByTagName('div'),
i,
div
for (i = 0; i < divs.length; i += 1) {
div = divs[i];
if (hasClass(div, 'photo')) {
// do something with the div
}
}
The hasClass function does its job well, so even when an element has multiple class names on it, such as:
<div class="popout photo frame">
The call to the above hasClass function in the above code will correctly match that element.
There’s the querySelector method which is native to javascript, butIE only started supporting that from IE8.
If you’re using a framework such as jQuery then there are standard ways using that.
Failing those options, you can get a group of tags in some way, such as with document.getElementsByTagName, and loop through them using this set of class handling functions: