Reputation: 3
I am having an HTML file where I have four input fields and none of them has an id. I want to change the value of those input fields. Below is the implementation of the input field. The index is different for all four input field.
<input class="digit" index="0" type="number" value="0" min="0" max="9">
I know how to do it if I have "id" by using below, but I dont know how to do if I dont have an id.
document.getElementById("myText").value = "Johnny Bravo";
I tried below but it's not working.
document.getElementsByClassName('digit').setAttribute("value", "2");
Upvotes: 0
Views: 668
Reputation: 2771
The getElementsByClassName()
returns a collection of elements. You can do something like this to change all the inputs of that class.
let digitElems = document.getElementsByClassName('digit');
Array.from(digitElems).forEach(function (el) {
el.setAttribute("value", 2);
})
<input class="digit" index="0" type="number" value="0" min="0" max="9">
<input class="digit" index="0" type="number" value="0" min="0" max="9">
<input class="digit" index="0" type="number" value="0" min="0" max="9">
<input class="digit" index="0" type="number" value="0" min="0" max="9">
Upvotes: 1
Reputation: 6534
use document.querySelector[All]()
and select the index
attribute
document.querySelector('input[index="0"]').value = 9;
<input class="digit" index="0" type="number" value="0" min="0" max="9">
<input class="digit" index="1" type="number" value="0" min="0" max="9">
Upvotes: 0