Display elements one by one from an array using jQuery


I will show you in this example, how to display elements one by one from an array using jQuery. Let’s say you have a button on the web page and on clicking the button the values from array will be displayed one by one. There are two examples below, one simply access the values from an array and another displays the images from an array.


jQuery 1.11.1/3.5.1


In our HTML code snippets I have just one div with button on the web page for clicking on it.

<div id="text-center">
	<button type="submit" id="btn">Click Here!</button>

jQuery Part

You need to include jQuery libraries in the head section of the HTML page. I am using the CDN link for jQuery libraries. You will find it when you download the source code from the given link at the bottom of this tutorial.

First Approach

Here I display each element on the page by clicking on the button. The element is extracted by calculating using modulo operator.

In this approach the element will be shown repeatedly.

	var values = [
	var counter = 0, totalElements = values.length;
	$("#btn").on("click", function(){			
		if(totalElements>1) {
			$('#text-center').append(values[counter] + ' ');
			counter = (counter + 1) % totalElements;

Second Approach

Here I will also show elements from array one by one on each click on the button but here the element will not be displayed repeatedly.

	var i=0, images = [
		"<img src='first.png' />",
		"<img src='second.png' />",
		"<img src='third.png' />",
		"<img src='kitten.png' />"

	$('#btn').on("click", function(){
		if (i>=images.length) return;

Final Result

The result is shown here for first approach only.

display array elements jquery

Source Code

Download source code

That’s all. Thank you for reading.

Leave a Comment