How to fetch nth div from an HTML page using jQuery?


To fetch the nth div from an HTML page, use the jQuery eq() method. It is used to access the index of an element in jQuery. The eq() method refers the position of the element.

Example

You can try to run the following code to learn how to fetch nth div from an HTML page using jQuery. Here, we will fetch the 2nd div:

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#button1").click(function(){
    alert($("div:eq(1)").text());
  });
});
</script>
</head>

<body>
<div>Paragraph One</div>
<div>Paragraph Two - 2nd div selected</div>
<div>Paragraph Three</div>
<button id="button1">Which div?</button>

</body>

Updated on: 09-Dec-2019

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements