andDev
andDev

Reputation: 275

Show elements from array in jquery

I'm new in web development. I converted the list of image names to an array by following codeL

var image_array = $("#image-ul img").map(function() {return $(this).attr("src");});

Now I want to show some of these images. I show all the images by adding following codeL

$('#image-ul img').css('display','block');

But I want some of the images, like the following:

for (var i=0; i<2; i++) { $('#image-ul img:image_array[i]').css('display','block');}

How can I do this?

Upvotes: 0

Views: 627

Answers (3)

Mark Walters
Mark Walters

Reputation: 12400

Change this line

for (var i=0; i<2; i++) { $('#image-ul img:image_array[i]').css('display','block');}

to this

for (var i=0; i<2; i++) { $('#image-ul img').eq(i).show(); }

as Juhana pointed out .show() is the best way to show display an element with jQuery

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388446

Try

for (var i=0; i<2; i++) { $('#image-ul img:eq(' + i +')').css('display','block');}

Or

for (var i=0; i<2; i++) { $('#image-ul img').eq(i).css('display','block');}

Upvotes: 1

adeneo
adeneo

Reputation: 318372

You don't really use a for loop to do that, you select the images and limit the selection with eq(), lt(), gt() etc. So for anyting with an index lower than 2, you do :

$('#image-ul img:lt(2)').show();

Upvotes: 3

Related Questions