2

In my code I have a function that accepts an array of JQuery collections and applies some code to each via a for-loop.

The problem is that as soon as I reference one it somehow becomes a HTMLDivElement instead of a collection object.

function vacant_now($timetables, now){
console.log("1:" + $timetables);//still fine
for (var i=0; i < $timetables.length; i++){
    console.log("2:" + $timetables[i]);//problem is here
    var $timetable = $timetables[i];
    console.log("3:" + $timetable);
    $timetable.find(".booking").each(function(){ ...

it's called like this:

vacant_now($page.find(".timetable"), now);

I'm stumped.

3 Answers 3

3

The jQuery collection array is an array of DOM elements.

Doing this: $('#myDiv')[0]; returns the same as: document.getElementByID('myDiv');

Solution: Use $('.timetable').eq(index);

for (var i=0; i < $timetables.length; i++){
    $timetables.eq(i);

}

Cheers

2

Using [i] on a jQuery object returns the dom element. If you want the jQuery object at a specific index use the .eq() function:

console.log("2:" + $timetables.eq(i));

Example - http://jsfiddle.net/8FeEf/1/

1

With jQuery you can use the .each method, and after you must 'jquerify' the object :

function vacant_now($timetables, now) {
    $timetables.each(function() {
        var $timetable = $(this);
    });
}

A jquery collection is in fact an array of DOM elements.

You can also use a for, the syntaxe is a little bit more verbose. In all case, you must jquerify the object.

Exemple : http://jsfiddle.net/FTcpD/

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.