9

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.

BSMP
  • 4,596
  • 8
  • 33
  • 44
Cagey215
  • 159
  • 1
  • 1
  • 8

3 Answers3

19
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.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • This worked perfect for me! Thank you everyone for the quick response. This was my first time ever posting on here and I was very surprised at how fast the responses are. To give everyone more detail. I had to make a Next button for Drupal Vertical Tabs. So the tabs are all created dynamically from Drupal core and the CSS hidden class is used by Drupal to keep track of which tab is the current tab. The core generates that CSS hidden class too. So I had to write JS to tap into the Drupal core to make the dynamic Next button. Thank you tymeJV! – Cagey215 Nov 05 '13 at 21:22
8

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");
  }
}
Archangel33
  • 496
  • 8
  • 22
  • 1
    **Archangel33**, I like the snippet above even though the solution above worked for me. I saved your snippet so I know how iterate through the array in the future. In case I need to target a different element. Thank you! – Cagey215 Nov 06 '13 at 15:03
1

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.

Anton Bessonov
  • 9,208
  • 3
  • 35
  • 38