jQuery API

jQuery.makeArray()

jQuery.makeArray( obj ) Returns: Array

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

  • version added: 1.2jQuery.makeArray( obj )

    objAny object to turn into a native 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.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<div>First</div>
  <div>Second</div>  
  <div>Third</div>

  <div>Fourth</div>
<script>
    var elems = document.getElementsByTagName("div"); // returns a nodeList
    var arr = jQuery.makeArray(elems);
    arr.reverse(); // use an Array method on list of dom elements
    $(arr).appendTo(document.body);
</script>
</body>
</html>

Demo:

Example: Turn a jQuery object into an array


    var obj = $('li');
    var arr = $.makeArray(obj);

Result:

(typeof obj === 'object' && obj.jquery) === true;
jQuery.isArray(arr) === true;
    

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for jQuery.makeArray() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • jackysee
    Can it be use for $.makeArray(arguments)?
  • No, but for that you can just do something like this:

    function arrayFromArgs() {
    return Array.slice.call(arguments);
    }

    and then call it:

    arrayFromArgs('3', '2', '4');