Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making js conditional statements shorter

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading