Change value attribute by class via JavaScript

54,065

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

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

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

Share:
54,065
Cagey215
Author by

Cagey215

Updated on August 01, 2022

Comments

  • Cagey215
    Cagey215 almost 2 years

    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.

  • Cagey215
    Cagey215 over 10 years
    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
    Cagey215 over 10 years
    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!