JS: Pass items from arrays as parameters for a function

Viewed 45

for example:

function example({array 1 item x}, {array 2 item x})

I'd imagine I'll need some sort of for loop that passes each item individually with the equivalent item from both arrays.

actual code:

function hide(bool, item) {
  if (bool) {
    document.getElementById(item).classList.add("hide");
    document.getElementById(item).classList.remove("show");
    bool = false;
  }
}

I need to run this for every id I want to hide and show, so I figured I could put the bools list and items list in an array and individually run them together to eliminate unnecessary redundancy.

1 Answers

If you want to hide and show element using one function call

this will hide or show multiple element by id

function showAndHide(bool, item) {
  if (bool.length !== item.length) throw new Error('bool and item length is different')

  bool.forEach((bool2, index) => {
    if (bool2) {
      document.getElementById(item[index]).classList.add("show");
      document.getElementById(item[index]).classList.remove("hide");
    } else {
      document.getElementById(item[index]).classList.add("hide");
      document.getElementById(item[index]).classList.remove("show");
    }
  })
}
Related