Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value attribute by class via JavaScript

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.

like image 777
Cagey215 Avatar asked Nov 05 '13 20:11

Cagey215


People also ask

How do you change attributes in JavaScript?

Another way to change or create an attribute is to use a method like element. setAttribute("attribute", "value") or element. createAttribute("attribute", "value"). Use setAttribute to change an attribute that has been defined before.

How do I change the value of an attribute?

To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.

How can I change an element's class with JavaScript?

The class name is used as a selector in HTML which helps to give some value to the element attributes. The document. getElementById() method is used to return the element in the document with the “id” attribute and the “className” attribute can be used to change/append the class of the element.

How do you change a class value in HTML?

Change the class value using className property The className property allows you to fetch an HTML element's class attribute value as a string. Using the className property allows you to change the class attribute value, but you need to add the previous value manually if you want to keep it.


3 Answers

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.

like image 61
tymeJV Avatar answered Oct 22 '22 05:10

tymeJV


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");
  }
}
like image 38
Archangel33 Avatar answered Oct 22 '22 05:10

Archangel33


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.

like image 29
Anton Bessonov Avatar answered Oct 22 '22 05:10

Anton Bessonov