jQuery Misc toArray() Method

jQueryWeb DevelopmentFront End Technology

The toArray() method in jQuery is used to get all the DOM elements contained in the jQuery set, as an array

Syntax

The syntax is as follows −

$(selector).toArray()

Let us now see an example to implement the jQuery toArray() method 

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $("button").click(function(){
         var arr = $("p").toArray()
         for (var k = 0; i< arr.length; k++) {
            alert(arr[k].innerHTML);
         }
      });
   });
</script>
</head>
<body>
<h2>Devices</h2>
<p>This is demo text 1.</p>
<p>This is demo text 2.</p>
<p>This is demo text 3.</p>
<p>This is demo text 4.</p>
<button>GET each p value</button>
</body>
</html>

Output

This will produce the following output −

On clicking the button, alter box generates with the first p-value −

On clicking OK again, the 2nd p-value will be visible−

In the same way, other values will be visible on pressing an OK button in the alert box.

raja
Published on 31-Dec-2019 09:13:54
Advertisements