Change value attribute by class via JavaScript

2020-06-16 02:57发布

I have the following 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".

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.

3条回答
我想做一个坏孩纸
2楼-- · 2020-06-16 03:06
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.

查看更多
干净又极端
3楼-- · 2020-06-16 03:10

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.

查看更多
冷血范
4楼-- · 2020-06-16 03:24

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");
  }
}
查看更多
登录 后发表回答