[SOLVED] use a function to not rewrite all ids


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.


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

Answered By – T.J. Crowder

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *