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

jQueryWeb DevelopmentFront End Technology

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>
raja
Published on 16-Dec-2017 08:42:01
Advertisements