jQuery toArray() Method

Last Updated:

jQuery toArray() Method

The jQuery toArray() method retrieves all the elements contained in the jQuery set, as an array.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery toArray() Method</h1> <div>1</div> <div>2</div> <div>3</div> <p>Click on the button and check you console.</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ var arr = $("div").toArray(); console.log($.type(arr)); console.log(arr); console.log(arr[0]); }); }); </script> </body> </html>

Syntax

$(selector).toArray();

Browser Support

Devicedesktopmobile
Browsergoogle chromesafarifirefoxinternet Exploreredgeoperagoogle chromesafarifirefoxedgeoperaandroid webviewsamsung internet
toArray()YesYesYesYesYesYesYesYesYesYesYesYesYes

Deep Understanding

In the following example, we will use jQuery's toArray() method and javascript's .innerText property to retrieves all the elements content as an array.

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>jQuery toArray() Method</h1> <div>1</div> <div>2</div> <div>3</div> <p>Click on the button and check you console.</p> <button>Click Me</button> <script> $(document).ready(function(){ $("button").click(function(){ var x = $("div").toArray(); var arr= []; for(i = 0; i < x.length; i++) arr.push(x[i].innerText); console.log(arr); }); }); </script> </body> </html>

Share this Page

Meet the Author