Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store several elements on a variable

Tags:

javascript

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");;
  }
like image 715
Biomehanika Avatar asked Jan 26 '26 01:01

Biomehanika


1 Answers

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

like image 101
John R Avatar answered Jan 27 '26 15:01

John R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!