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.
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);
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With