How to get the element by index in jQuery ?

Getting element by index in jQuery

$("tag:eq(index)") is used to access the element by index.

eq function is used to select an element with a specified index.

$("p:eq(3)")

Gets the fourth paragraph element from the list of paragraph elements in document. here index is 3 but index starts from 0, so 4th element is matched.

Example jQuery code to the element by index

<html>
   <head>
      <title>The jQuery Example - To get the element by index </title>

 <script src="https://code.jquery.com/jquery-1.10.2.js"></script>	
      <script type = "text/javascript">
        function get_matching_element() {
          var content= $("p:eq(3)").html();
	  alert("p element with index 3 content: " + content);
        }
      </script>		
   </head>	
   <body>
<p>line 0</p>
<p>line 1</p>
<p>line 2</p>
<p>line 3</p>
<p>line 4</p>
<p>line 5</p>
<p>line 6</p>
<input type="button" value="Get Element" onclick="get_matching_element();"/>
   </body>
</html>
Output:
get element by index output

Gets fourth paragraph element text when clicking on 'Get Element' button.

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^