0

how to get a collection of elements?

var tst = this.tbl_list.find('col');
alert('length = '+tst.length);
for(var key in tst){
    alert(tst[key][0].tagName);
}

this alerts length = 7 (which is the correct count), but each element is undefined!?

clarkk
  • 27,151
  • 72
  • 200
  • 340

6 Answers6

3

This is because when you're using for in, you're iterating over all the jQuery methods as well (find, children etc); and none of these have [0].tagName (for more info as to why see JavaScript for...in vs for).

Instead, you should either use each(), or use a for (;;;) loop;

var tst = this.tbl_list.find('col');
alert('length = '+tst.length);
for(var i=0;i<tst.length;i++){
    alert(tst[i].tagName);
}

You can see the difference in using them in this JSFiddle; http://jsfiddle.net/nTCSY/

Using each(), you'd have;

tst.each(function () {
    alert(this.tagName);
});
Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180
3

It's hard to say what's going wrong without seeing your mark-up, but something like this should work -

tst.each(function() {
   alert(this.tagName)
});

Demo - http://jsfiddle.net/UjfUy/1/

ipr101
  • 24,096
  • 8
  • 59
  • 61
1

Maybe you need each

Mike
  • 1,042
  • 1
  • 8
  • 14
0

Do it like so (using jQuery):

var elements = this.tbl_list.find('col'); 

$.each(elements, function(index, element){
   alert(element.tagName);
});
Bas Slagter
  • 9,831
  • 7
  • 47
  • 78
0

Try this:

var tst = this.tbl_list.find('col');
alert('length = '+tst.length);
for(var i=0;i<tst.length;i++){
    alert(tst[i].tagName);
}
jerjer
  • 8,694
  • 30
  • 36
0

Use .get() or .eq() to get single elements from the collection of dom objects.

var tst = this.tbl_list.find('col');

alert('length = '+ tst.length);
for(i=0; i< tst.length ; i++  ){
   alert(tst.get(i).tagName);

 //or tst.eq(i)
}

another way is .each() iterate through dom elements.

.each() method is designed to make DOM looping constructs concise .

e.g.

$('li').each(function(index) {
    alert(index + ': ' + $(this).text());
});

for your solution this should be like this:

tst.each(function() {
   alert(this.tagName)
}); 
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75