Change value attribute by class via JavaScript

女生的网名这么多〃 提交于 2020-05-10 09:28:47

问题


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.


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/19798742/change-value-attribute-by-class-via-javascript

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