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.
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.
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.
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.
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.
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.
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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With