Reputation: 27689
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
!?
Upvotes: 0
Views: 289
Reputation: 75307
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);
});
Upvotes: 3
Reputation: 18290
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)
});
Upvotes: 0
Reputation: 24236
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/
Upvotes: 3
Reputation: 8760
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);
}
Upvotes: 0
Reputation: 9929
Do it like so (using jQuery):
var elements = this.tbl_list.find('col');
$.each(elements, function(index, element){
alert(element.tagName);
});
Upvotes: 0