Html 通过 JavaScript 按类更改值属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19798742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change value attribute by class via JavaScript
提问by Cagey215
I have the following HTML:
我有以下 HTML:
<input class="vertical-tabs-active-tab" type="hidden" value="account" name="tabs__active_tab">
I need JavaScript that will change the value of "account" to "yolo".
我需要将“帐户”的值更改为“yolo”的 JavaScript。
I thought I could do this:
我以为我可以这样做:
document.getElementsByClassName('vertical-tabs-active-tab').setAttribute("value", "yolo");
But that produces an error of:
但这会产生以下错误:
document.getElementsByClassName(...).setAttribute is not a function
I'm not able to add an "id" to input, I have to change the value based on class.
我无法在输入中添加“id”,我必须根据类更改值。
回答by tymeJV
document.getElementsByClassName('vertical-tabs-active-tab')[0].setAttribute("value", "yolo");
document.getElementsByClassName
returns an array of elements, specify the index of the element you wish to change.
document.getElementsByClassName
返回一个元素数组,指定要更改的元素的索引。
回答by Archangel33
This may do what you want:
这可能会做你想做的:
var elms = document.getElementsByClassName('vertical-tabs-active-tab')
for (var i = 0; i < elms.length; i++) {
if (elms[i].getAttribute("value") === "account"){
elms[i].setAttribute("value", "yolo");
}
}
回答by Anton Bessonov
getElementsByClassName return a list/array of elements. Pick element through index and set value on it. You can also iterate over elements. getElementById return only one element.
getElement sByClassName 返回元素列表/数组。通过索引选择元素并在其上设置值。您还可以迭代元素。getElementById 只返回一个元素。