Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  189] [ 1]  / answers: 1 / hits: 22936  / 11 Years ago, sat, december 28, 2013, 12:00:00

I need set value of a bunch of input boxes based on class (class=Qty)



this works if I use the ElementID



document.getElementById('G_Qty_0').value='101'


but this doesn't work



document.getElementsByClassName('Qty').value='100'


What gives?



Cheers!


More From » html

 Answers
30

document.getElementsByClassName returns a NodeList, not an individual element. You can loop through the list, e.g.:



var list = document.getElementsByClassName('Qty');
var n;
for (n = 0; n < list.length; ++n) {
list[n].value='100';
}


Or if you know there will be only one match (and you know there won't be zero matches):



document.getElementsByClassName('Qty')[0].value = '100';


You might also look at querySelector and querySelectorAll, because they're actually better-supported than getElementsByClassName (specifically: IE8 supports them, but doesn't have getElementsByClassName). querySelector looks for the first element in the document that matches the given CSS selector and returns that element instance (or null if there are none). querySelectorAll returns a NodeList of all matching elements. (That NodeList is not quite the same as the one returned by getElementsByClassName, in that it's a snapshot as of when you make the call, not a live NodeList).



So for instance:



document.querySelector('.Qty').value = '100';


Or:



var list = document.querySelectorAll('.Qty');
var n;
for (n = 0; n < list.length; ++n) {
list[n].value='100';
}

[#73515] Thursday, December 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeffery

Total Points: 180
Total Questions: 114
Total Answers: 117

Location: Chad
Member since Mon, Dec 5, 2022
1 Year ago
;