I’ve been messing around with a wp plugin that is missing some classes and stuff, and I figured I could add them myself through a custom script.
As you can see from the code I just selected a bunch of elements and I gave each one a unique classname that will later be used to add some css pseudo elements, but the best thing I could come up with is this long a55 statement lol
If some of you know a better way, your help will be greatly appreciated!
This is an html snippet of my area of interest:
<div class="side_by_side">
<label for="fieldname6_1_rb7">
<input
aria-label="Van"
name="fieldname6_1"
id="fieldname6_1_rb7"
class="field group required"
value="489"
vt="Van"
type="radio"
/>
<span>Van</span></label>
</div>
This is what my js looks like, which works as it is, but I’d like to know if there’s a better way to write something like this..
const modelInputLabel = document.querySelectorAll(".side_by_side span");
for (let i = 0; i < modelInputLabel.length; i++) {
if (i === 0) {
modelInputLabel[i].setAttribute("class", "test modelFirst");
} else if (i === 1) {
modelInputLabel[i].setAttribute("class", "test modelSecond");
} else if (i === 2) {
modelInputLabel[i].setAttribute("class", "test modelThird");
} else if (i === 3) {
modelInputLabel[i].setAttribute("class", "test modelFourth");
} else if (i === 4) {
modelInputLabel[i].setAttribute("class", "test modelFifth");
} else if (i === 5) {
modelInputLabel[i].setAttribute("class", "test modelSixth");
} else if (i === 6) {
modelInputLabel[i].setAttribute("class", "test modelSeventh");
} else if (i === 7) {
modelInputLabel[i].setAttribute("class", "test modelEight");
}
}
>Solution :
Using forEach and index
const classNames = ["test modelFirst",
"test modelSecond",
"test modelThird",
"test modelFourth",
"test modelFifth",
"test modelSixth",
"test modelSeventh",
"test modelEight"];
const modelInputLabel = document.querySelectorAll(".side_by_side span");
modelInputLabel.forEach((modelInput, index) => {
modelInput.setAttribute("class", classNames[index]);
});