3gwebtrain
3gwebtrain

Reputation: 15303

jQuery: Is there any way to select multiple elements using an array selector?

Is it possible to select multiple elements using an array selector?

If so, what is the best way to do it? In my project, I need to use only array selectors.

This is my sample code:

<ul>
    <li>1<li>
    <li>2<li>
    <li>3<li>
    <li>4<li>
    <li>5<li>
</ul>
<a href="#">select</a>​

$('a').click(function(){
    var element = $('ul').find('li')[0]; // Instead is it possible $('ul').find('li')[0,3,4]? I know we can select finding each alone. But is there any shortcut?
    $(element).css({border:'1px solid red'});
})​

Upvotes: 0

Views: 7035

Answers (6)

sp00m
sp00m

Reputation: 48837

Here is a sexy way to do it: add a custom method to the JavaScript Array object as suggested in another answer.

Array.prototype.filter = function(indexes) {
    var array = new Array();
    for(var i=0; i<indexes.length; i++) {
        array.push(this[indexes[i]]);
    }
    return array;
};

To call it:

$('ul').find('li').filter([0,3,4]).anything();

Custom generic shortcut as you wished :)

Upvotes: 1

Vytautas
Vytautas

Reputation: 3539

Maybe this will work (but not so good with performance):

$('ul li:nth-child(0),ul li:nth-child(2)');

Or this:

$('ul li:eq(0),ul li:eq(2)');

Upvotes: 0

Robin Castlin
Robin Castlin

Reputation: 10996

This would give desired result. Simply filter by index() and use inArray().

var arr = [0, 3, 5];
$('ul li').each(function() {
    if ($.inArray($(this).index(), arr) < 0)
        return;
    // Code here!
    $(this).css('border', '1px solid red');
});

Basicly all the <li> are run through the each() and then I loop to check if given .index() is in given array. If they don't exist ( $.inArray() == -1 ) then I do a return; to skip execution.

Upvotes: 7

Stefan
Stefan

Reputation: 5662

One option is to use filter;

var indexArray = [1,3,4];
$('ul li').filter(function(index) {
    return jQuery.inArray($(this).index(), indexArray) > -1;
});

Also using $.inArray and index(). View demo.

Upvotes: 1

Sebastian
Sebastian

Reputation: 1199

loop it

$('a').click(function() {
    var element = $('ul').children('li');
    var count = 0;
    for (x in element) {
        count++;
        if ((count == 0) || (count == 3) || (count == 5))
            x.css({ border: '1px solid red' });
    }
});

Upvotes: 0

Ranganadh Paramkusam
Ranganadh Paramkusam

Reputation: 4368

You can use forEach of array also

arr = "013".split("");
arr.forEach(function(a,b){
    var element = $('li')[a]; 
    console.log(element);
    $(element).css({border:'1px solid red'});
});

Here's Fiddle

Upvotes: 0

Related Questions