0

I am using getElementsByClassName to get a collection of tr.

I want to now iterate through the collection and get the value of a textbox in the tr.

I cannot use JQuery to do this or any other framework.

How can this be done?

var dom = document.getElementsByClassName('Row');
var arr = [];
var len = dom.length;
for (var i = 0; i < len; i++) {
   // foo = look up value of a text box in this row 
   // bar = look up value of a text box in this row 
   var obj = {
   quantity: foo,
   price: bar
   };
 arr.push(obj);
}
3
  • 2
    developer.mozilla.org/en-US/docs/Web/API/… Commented Aug 24, 2013 at 6:26
  • Link above is important to note, as getElementsByClassName is only from IE9 and onwards Commented Aug 24, 2013 at 8:28
  • Thanks, I am not actually using getElementsByClassName but put it in to simplify the example. I am using a YUI method that returns exactly the same thing @MackieeE @mu is too short Commented Aug 24, 2013 at 8:36

1 Answer 1

2

Firstly, it's getElementsByClassName, with an 's' -- it can get more than one element, so its name is a plural.

Secondly, getElementsByClassName is not a function on it's own, it's a method on a DOM object.

If you want to get all elements in the document that match a given class name, you have to call document.getElementsByClassName(), not just getElementsByClassName() on its own.

So you need to do this:

var dom = document.getElementsByClassName('Row');

The elements within the dom object you get back from this also has the same methods available as the root document object, you can can call dom[i].getElementsByClassName(), etc.

For example, in order to get all the textarea elements within it, you could do dom[i].getElementsBtTagName('textarea').

That should help get you going.

Sign up to request clarification or add additional context in comments.

4 Comments

Apologies, you are correct & my mistake. How can I now look up a textbox in a tr when I iterate through the colllection @Spudley
@ojhawkins - I've added a bit more to the answer, to try to help a bit more.
Should I be able to use dom[i].getElementById('foo')? @Spudley
yep, that would work too; any of the dom methods should work. (although specifically getElementById() would be less useful, since an ID is supposed to be unique on a page so it shouldn't be necessary to call by ID from here as the result would be the same as calling from document)

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.