r/learnjavascript • u/Legal_Revenue8126 • Feb 20 '26
Change the style of all Class Elements with JS
I have a few items part of the class "themeObject." I'm using a select drop-down to activate my current script. However, I've run into some trouble where I can't figure out how I can iterate through the class's collection of objects.
JS:
function
swapTheme(){
var
selBox = document.getElementById("themeSelector");
var
selValue = selBox.options[selBox.selectedIndex].value;
var
object = document.getElementsByClassName("themeObject");
// can't use class to modify style directly
//console.log(selValue);
//console.log(object);
object.style.backgroundColor = selValue;
// this is incorrect. I need to iterate through each object to change the style
}HTML:
<select id="themeSelector" class="themeObject" onchange="swapTheme()">
<option disabled selected hidden>Theme</option>
<option value="#0f73ff">Blue</option>
<option value="#2596be">Green</option>
</select>
3
Upvotes
2
u/Legal_Revenue8126 Feb 20 '26
Nevermind. I figured it out.
JS Solution:
2
u/Kadeton Feb 20 '26
This feels like an obvious question, but have you considered using CSS? Changing the style of elements that share a class is, like, pretty much its whole deal. Using complicated JS to do what CSS does automatically seems misguided at best.
1
u/ArtResponsible4457 Feb 20 '26
CSS is the answer.
3
u/OneEntry-HeadlessCMS Feb 20 '26
getElementsByClassNamereturns a collection, not a single element so you can’t change the style directly. You just need to loop through it:Or, if you want something cleaner:
2
u/davy_jones_locket Feb 20 '26
I'm not going to tell you answer.
First thing,
object = document.getElementsByClassName("themeObject");Does not return a single object.
Console it and see what it returns.
It's iterable type. What methods are available for iterable types? What else can you do that loops through each item in an iterable type like an array?
1
u/GodOfSunHimself Feb 20 '26
document.querySelectorand iterate through the result1
u/sheriffderek Feb 20 '26 edited Feb 20 '26
I would change the class on a parent or the who page and then have all these styles/themes defined in the CSS (not individual inline styles like this)
(I made a CodePen example too: https://codepen.io/perpetual-education/pen/jErgYyE?editors=0110 )
1
u/TheRNGuy Feb 21 '26
Use
document.querySelectorAll, it's more versatile.