简体   繁体   中英

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.

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

when you use $('.myclass')[v] you are getting the actual DOM object at index v

you could use below instead of trying to use an array notation

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

:eq doc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM