document.getElementsByTagName not working

前提是你 提交于 2019-12-23 04:45:41

问题


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


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/35661807/document-getelementsbytagname-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!