Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: select element with classname and node index

I have a bunch of elements with the class ".myclass". Now I'd like to select one of these elements by its node index and animate it. I get an error that says the element has no function animate.

example:

<div class="myclass"></div>
<div class="myclass"></div>
<div class="myclass"></div>

var indizes = [0, 3];

$.each(indizes, function(i, v) {
    $('.myclass')[v].animate({
        left: 100
    }, 1000);
});

Apparently the error comes from using a wrong selector. It does work if I use

$($('.myclass')[v])

instead of

$('.myclass')[v]

Is this the actual problem? It seems so weird to me to nest selectors.

like image 624
Timo Avatar asked Aug 04 '13 14:08

Timo


2 Answers

Is this the actual problem?

Yes. If you access a selected element via bracket notation, you get the raw DOM element back. DOM elements don't have an animate method. By passing the DOM element to jQuery again ($($('.myclass')[v])) you are creating a jQuery object (again).

You can avoid this and use .eq to get a jQuery object for the element at that index:

$('.myclass').eq(v);

It would be better to keep a reference to the selected elements outside the loop though:

var indizes = [0, 3];
var $elements = $('.myclass');

$.each(indizes, function(i, v) {
    $elements.eq(v).animate({
        left: 100
    }, 1000);
});

Alternatively, you can use .filter to filter out the elements you want to animate, which at least looks a bit more concise:

$('.myclass').filter(function(i) {
    return $.inArray(i, indizes) > -1;
}).animate({
    left: 100
}, 1000);
like image 110
Felix Kling Avatar answered Oct 27 '22 00:10

Felix Kling


You are doing everything right, and yes you do have to re-wrap the element like so.

var indizes = [0, 3],
    elements = $('.myclass');

$.each(indizes, function(i, v) {
    $(elements[v]).animate({
        left: 100
    }, 1000);
});

When you do $('.myclass')[0] then that element doesn't have any jQuery methods attached to it anymore

like image 22
iConnor Avatar answered Oct 27 '22 01:10

iConnor