I would like to use document.getElementsByTagName('input')
to set as required (or unset it) for a list of inputs.
is it possible?
I've tried:
document.getElementsByTagName('input').required = false;
or (for a different purpose)
document.getElementsByTagName('input').value = ""
but it doesn't seem work.
Moreover: is it possible to catch a certain type of input (i.e. text or radio)?
Thank you!!! ObOnKen
I would like to use document.getElementsByTagName('input')
to set as required (or unset it) for a list of inputs.
is it possible?
I've tried:
document.getElementsByTagName('input').required = false;
or (for a different purpose)
document.getElementsByTagName('input').value = ""
but it doesn't seem work.
Moreover: is it possible to catch a certain type of input (i.e. text or radio)?
Thank you!!! ObOnKen
Share Improve this question edited Feb 26, 2016 at 21:23 ak_ 2,8153 gold badges16 silver badges28 bronze badges asked Feb 26, 2016 at 21:10 Ob On KenOb On Ken 351 gold badge1 silver badge10 bronze badges 1- 1 It returns an HTMLCollection developer.mozilla/en-US/docs/Web/API/Element/… – PeeHaa Commented Feb 26, 2016 at 21:13
4 Answers
Reset to default 4getElementsByTagName()
returns a collection of elements so you need to iterate over the collection...
var elements = document.getElementsByTagName('input');
for(var i = 0; i < elements.length; i++)
{
if(elements[i].type == "text")
{
elements[i].value = "";
}
}
getElementsByTagName()
returns a live HTMLCollection. If you want to do something to each item returned, you'll have to explicitly iterate across them:
var inputs = table.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].required = false;
}
However, if you use some libraries, you may be able to operate on each of the contents of a collection (or, as some of the libraries call them, selection) en-masse with a syntax as you seem to expect.
You should use for
loop for iterating all input
s, because document.getElementsByTagName
returns a HTMLCollection
of elements with the given tag name.
var values = document.getElementsByTagName('input');
for (var i = 0; i < values.length; i++) {
values[i].required = false;
}
To catch a certain type of input:
var textInput = document.querySelector("input[type=text]");
querySelector
returns the first element within the document.
If you have multiple input elements in your document,then you use document.getElementByTagName:for this you've to use for loop to iterate over multiple elements. or if you've only one element then you can use queryselector with given Id/Classname like:if you've I'd in your element:document.querySelector("idname"); or you've class in your element: document.querySelector("className");
You can also use (in case of one element) document.getElementById("idname"); if you've given Id to your element