jQuery.makeArray()


jQuery.makeArray( obj )Returns: Array

Description: Convert an array-like object into a true JavaScript array.

Many methods, both in jQuery and in JavaScript in general, return objects that are array-like. For example, the jQuery factory function $() returns a jQuery object that has many of the properties of an array (a length, the [] array access operator, etc.), but is not exactly the same as an array and lacks some of an array's built-in methods (such as .pop() and .reverse()).

Note that after the conversion, any special features the object had (such as the jQuery methods in our example) will no longer be present. The object is now a plain array.

Examples:

Example: Turn a collection of HTMLElements into an Array of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.makeArray demo</title>
<style>
div {
color: red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div>First</div>
<div>Second</div>
<div>Third</div>
<div>Fourth</div>
<script>
// Returns a NodeList
var elems = document.getElementsByTagName( "div" );
// Convert the NodeList to an Array
var arr = jQuery.makeArray( elems );
// Use an Array method on list of dom elements
arr.reverse();
$( arr ).appendTo( document.body );
</script>
</body>
</html>

Demo:

Example: Turn a jQuery object into an array

1
2
var obj = $( "li" );
var arr = $.makeArray( obj );

Result:

1
2
( typeof obj === "object" && obj.jquery ) === true;
jQuery.isArray( arr ) === true;