Biomehanika
Biomehanika

Reputation: 1540

Store several elements on a variable

I have created a styling reset as the first part of a form validation. I must clear two types of elements: inputs and select. Can I store on a variable two kinds of elements? So that inputs var stores both inputs and select objects.

  var inputs = document.getElementsByTagName("input");
  var totalInputs= inputs .length;

  for (var i = 0; i < totalInputs; i++){
        inputs[i].removeAttribute("style");;
  }

Upvotes: 3

Views: 1085

Answers (2)

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

The getElementsByTagName returns a node list. I would suggest using querySelectorAll to get the input and select elements.

var inputs = document.querySelectorAll("input,select"));
var totalInputs = inputs.length;

for (var i = 0; i < totalInputs; i++){
    inputs[i].removeAttribute("style");;
}

Upvotes: 0

John R
John R

Reputation: 2801

You can store multiple elements in the single variable by using querySelectorAll only. But not by using getElementsByTagName.

Here you can store both input and select objects by,

var inputs = document.querySelectorAll("input,select");

Check this example:

$(function() {
  $("button").click(function() {
    var inputs = document.querySelectorAll("input,select");
    var totalInputs = inputs.length;
    for (var i = 0; i < totalInputs; i++) {
      inputs[i].removeAttribute("style");;
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" style="background:#b6ff00" />
<select style="background:#b6ff00">
  <option>Option 1</option>
  <option>Option 2</option>
</select>
<button>Remove</button>

Hope this helps

Upvotes: 3

Related Questions