How to use attributes getElementsByTagName and setAttribute

0

I have a form of two fields with I want that when I press a button both fields are placed in red background, until now I have this code but it does not work

function validacion(){
var valor = document.getElementsByTagName("input");
valor.setAttribute("style", "background-color: red;");
}
    <form>
<input type="text" placeholder="texto" id="1" name="uno" class="caja"/>
<input type="text" placeholder="texto" id="2" name="dos" class="caja"/>
<input type="submit" value="aqui" onclick="return validacion()"/>
</form>

What happens is that I still need to be assigned to all the input so I use the getElementByTagName

    
asked by Nestor Bautista 04.01.2018 в 20:48
source

1 answer

0

What happens is that by doing document.getElementsByTagName("input") this will return a Array with all the input there is, and you are only assigning it to a variable that is not of the type > Array . After assigning that to a Array , what you should do is go through it and do the color change.

function validacion(){
  let valor = document.getElementsByTagName("input");

  for (let i = valor.length - 1; i >= 0; i--) {
    valor[i].setAttribute("style", "background-color: red;");
  }
}
<form>
  <input type="text" placeholder="texto" id="1" name="uno" class="caja"/>
  <input type="text" placeholder="texto" id="2" name="dos" class="caja"/>
<input type="submit" value="aqui" onclick="return validacion()"/>
</form>

or as the partner said

    function validacion(){
            for(var input of document.getElementsByTagName('input')){
                input.setAttribute("style", "background-color: red;");
            }
         }
    
answered by 04.01.2018 / 20:56
source