Change value attribute by class via JavaScript

Cagey215 picture Cagey215 · Nov 5, 2013 · Viewed 51.2k times · Source

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.

Answer

tymeJV picture tymeJV · Nov 5, 2013
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.