jQuery - Display elements by Indexing in Array




We already know that we can access the first element and last element using :first and :last qualifires. But what, if we wish to access the second or fifth element ? Well you can assign the slection in a javascript variable and the trick is to assign it as an array. You can then access the individual element of the array .

As an example the folllwoing code


var element = $("img")[2];




will set the variable element to the second <img> element in the matched set of document's all <img> elements.

Take a look at the following example


<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
       
 x=$("p")[2];
 alert(x.innerHTML);
  });
});
</script>
</head>
<body>
<button>Alert  the value of the third item</button>
<p>Pasta</p>
<p>Rice</p>
<p>Coke</p>
<p>Pizza</p>
</body>
</html>


You may like to try this example online to see it in action - here.