Ob On Ken
Ob On Ken

Reputation: 35

document.getElementsByTagName not working

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

Upvotes: 0

Views: 14807

Answers (4)

user21866915
user21866915

Reputation: 1

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

Upvotes: 0

isvforall
isvforall

Reputation: 8926

You should use for loop for iterating all inputs, 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.

Upvotes: 0

Vynce
Vynce

Reputation: 3236

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.

Upvotes: 1

brso05
brso05

Reputation: 13222

getElementsByTagName() 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 = "";
    }
}

Upvotes: 4

Related Questions