[英]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. 因此inputs
var存储输入和选择对象。
var inputs = document.getElementsByTagName("input");
var totalInputs= inputs .length;
for (var i = 0; i < totalInputs; i++){
inputs[i].removeAttribute("style");;
}
You can store multiple elements in the single variable by using querySelectorAll
only. 您只能使用querySelectorAll
在单个变量中存储多个元素。 But not by using getElementsByTagName
. 但不是通过使用getElementsByTagName
。
Here you can store both input
and select
objects by, 在这里,您可以存储input
和select
对象,
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 希望这可以帮助
The getElementsByTagName
returns a node list. getElementsByTagName
返回节点列表。 I would suggest using querySelectorAll
to get the input and select elements. 我建议使用querySelectorAll
来获取输入和选择元素。
var inputs = document.querySelectorAll("input,select"));
var totalInputs = inputs.length;
for (var i = 0; i < totalInputs; i++){
inputs[i].removeAttribute("style");;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.