I'm looking to add a class to each element within an array I have using pure javascript only. My need for this is because I the application I have gives me 'very' limited html editing capability.
My Goal
" Is to emulate radio buttons by using checkboxes. "
To do this I need to add a uniqe class handle to all the elements I want to target, as not to pick up any other elements by mistake. Only then can I start manipulating thier behavior.
Essentially what I realise I need is to loop - // .classList.add("chkbox");
through the array applying .chkbox
to each of the elements within it.
The only issue is, I'm unsure of the best way to do this. I've done some digging around and couldn't find anything that really matched what I'm looking for. "However, I did find this handy dandy post here about arrays!"
I think I understand how to loop through an array, but how do I target the elements within individually?
// Place elements within an array ...
var a = document.getElementsByTagName("input");
var b = []; // Contains all checkboxes ...
for (var i = 0; i < a.length; i++) {
if (a[i].type == "checkbox") {
b.push(a[i]);
}
};
console.log(a);
console.log(b);
// .classList.add("classToBeAdded");
I'm not too saavy with JS so any help I could get with this issue would be awesome, and I'll give my thanks in advance.
Regards, - B.
NOTE 04 Oct:
classList.add('class') isn't supported by all browsers indeed. The element.setAttribute('class', 'here_the_class'); is better supported.
– Camille Sébastien Niessen
NOTE 05 Oct:
For those that find this thread in passing, if you're interested in the finished result, you can find an updated Jsfiddle here.
– Beaniie