简体   繁体   English

通过JavaScript按类更改值属性

[英]Change value attribute by class via JavaScript

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". 我需要JavaScript将“帐户”的值更改为“yolo”。

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”,我必须根据类更改值。

document.getElementsByClassName('vertical-tabs-active-tab')[0].setAttribute("value", "yolo");

document.getElementsByClassName返回元素数组,指定要更改的元素的索引。

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

getElement s ByClassName return a list/array of elements. getElement s ByClassName返回一个列表/数组元素。 Pick element through index and set value on it. 通过索引选择元素并在其上设置值。 You can also iterate over elements. 您还可以迭代元素。 getElementById return only one element. getElementById只返回一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM