jquery: select element with classname and node index

javascript, jquery, jquery-selectors

Solution

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);

Problem

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.

Original source