-1

I am still the begininer in javascript.. I guess it can be written simpler, without retyping those IDs. Html file has got matching ids to clear after the form is resulted.

function deleteValues() {
    document.getElementById('firstFemale').value = "";
    document.getElementById('secondFemale').value = "";
    document.getElementById('thirdFemale').value = "";
    document.getElementById('mistakeFemale').innerHTML = "";
    document.getElementById('resultFemale').innerHTML = "";
    document.getElementById('firstMale').value = "";
    document.getElementById('secondMale').value = "";
    document.getElementById('thirdMale').value = "";
    document.getElementById('mistakeMale').innerHTML = "";
    document.getElementById('resultMale').innerHTML = "";
}

but what if I had a lot of different IDs? I know getElementbyId can only retract one element. Any help is appreciated.

  • 2
    For the inputs `document.getElementById("yourFormId").reset();` or `` For innerHTML, common class and a forEach – epascarello Feb 01 '22 at 14:05
  • [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – isherwood Feb 01 '22 at 14:06
  • @epascarello - Darned fine idea, if they're in a `form` and their default values are `""`. But it's not going to help with the `innerHTML` ones. – T.J. Crowder Feb 01 '22 at 14:06

1 Answers1

1

You can take multiple approaches, but I'd probably add a class to the elements so you get could get a list of them. For instance, you might give them the class to-clear (class="to-clear") and then:

document.querySelectorAll(".to-clear").forEach(element => {
    if ("value" in element) {
        element.value = "";
    } else {
        element.innerHTML = "";
    }
});

More: querySelectorAll

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875