I have these 3 Boxes with the same classes and a button:
function turnRedAndAddPadding() {
/* ??? */
}
.box {
border: 1px solid;
display: inline;
}
<button onclick="turnRedAndAddPadding();">Press</button>
<div class="box">Box 1</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
I want to add styles to the class .box
when clicking on the button without adding a new class to the boxes. Basically, if you press the button, the class .box
should get a red background color and a padding and all the elements that have this class should have the same. Is there an easy way in JavaScript to solve this problem?
Thanks in advance.
4
Answers
Some really useful documentation by W3 Schools talks about how to use
getElementsByClassName
which you can find here You can find about editing the padding as well from here via the padding property of each element.Below I am finding all div’s that have the class box. Then iterating over each of them and assigning the colour and padding. You can change this to your liking.
There are also many other properties that you can edit for each DOM element like divs!
Just adding some javascript you can achieve your goal.
document.querySelectorAll
with this you can collect all elements with classbox
and then loop with a foreach functionBased on that post you could try something like this:
Hope it helps.
You don’t really want to add properties to the existing class. What you should do is add a new class that contains those red/padding properties to each element’s class list.
Toolkit
You need some way to "pick up" the elements for processing. Since you have more than one
querySelectorAll
is probably the go-to choice which will give you a static nodelist (rather than a live HTML collection that methods likegetElementsByClassName
give you which have some side-effects if you don’t use them correctly.)You’ll want a way to iterate over the elements to the processing. There are a number of possibilities provided in that link but
forEach
is a good choice here.You’ll want a way to update the class list of each element in the iteration. The unsuprisingly-named
classList
has, among its methods,add
which accepts a string of the CSS class you want to add.Define a new class ("redpad" in this example) that can be used.
Finally, because you want to avoid inline JS in 2023, you should be using
addEventListener
which accepts a) an event type and b) the name of the function you want to call when that event is fired.