5

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!

2 Answers 2

12

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';
}
Sign up to request clarification or add additional context in comments.

2 Comments

@MaxHodges - an easy reminder, if it says getElements with an s, it's always a nodeList.
@adeneo yes I understood that, just didn't know how to loop. I'm executing this in the browser console, and thought it could be done in theory, but my JavaScript knowledge is pretty weak still.
2

Since this question comes up among the first results on Google and I found a shorter solution, I'm writing it here for the benefit of those looking for a shorter code:

document.querySelectorAll('.Qty').forEach( (x) => { x.value = '100' } )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.