jQuery | Misc toArray() Method
The toArray() Method in jQuery is used to return the elements that are matched by the jQuery selector as an array.
Syntax
$(selector).toArray()
Parameters: This method does not accept any parameters.
Example 1: This method uses toArray() method to display the paragraph in form of array.
<!DOCTYPE html> < html > < head > < title > jQuery Misc toArray() Method </ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > w3wiki </ h1 > < h2 >jQuery Misc toArray() Method</ h2 > < button >Click</ button > < p >Beginner1</ p > < p >Beginner2</ p > < p >Beginner3</ p > <!-- Script to use toArray() method --> < script > $(document).ready(function() { $("button").click(function() { var i; var x = $("p").toArray() for (i = 0; i< x.length ; i++) { alert(x[i].innerHTML); } }); }); </script> </ body > </ html > |
Output:
- Before Click on the button:
- After Click on the button:
Example 2: This example use toArray() method to display the array element.
<!DOCTYPE html> < html > < head > < title > jQuery Misc toArray() Method </ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </ script > </ head > < body style = "text-align:center" > < h1 style = "color:green;" > w3wiki </ h1 > < h2 >jQuery Misc toArray() Method</ h2 > < button >Click</ button > < p >Beginner1-Beginner2-Beginner3</ p > < div style = "color:lightgreen;" ></ div > <!-- This example use toArray() method --> < script > $(document).ready(function(){ $("button").click(function(){ var i; var x = $("p").toArray() for (i = 0; i< x.length ; i++) { $("div").text(x[i].innerHTML); } }); }); </script> </ body > </ html > |
Output:
- Before Click on the button:
- After Click on the button: