jQuery API

.toArray()

.toArray() Returns: Array

Description: Retrieve all the DOM elements contained in the jQuery set, as an array.

  • version added: 1.4.toArray()

.toArray() returns all of the elements in the jQuery set:

alert($('li').toArray());

All of the matched DOM nodes are returned by this call, contained in a standard array:

[<li id="foo">, <li id="bar">]

Example:

Selects all divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that array.

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

  <div>One</div>
  <div>Two</div>
  <div>Three</div>
<script>

    function disp(divs) {
      var a = [];
      for (var i = 0; i < divs.length; i++) {
        a.push(divs[i].innerHTML);
      }
      $("span").text(a.join(" "));
    }
    
    disp( $("div").toArray().reverse() );
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .toArray() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .toArray()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • Joel

    Is this different from .get() in some way, or just another name for the same thing?

    • http://ejohn.org/ John Resig

      Yep, it's identical to .get(), just a different (and more usable) name. Although, .get() takes an argument for retrieving a single element and .toArray() does not.

    • http://bobbonifield.com Bob Bonifield

      Just some sugga!

  • AreN

    You can treat a jQuery object as an array in some cases, however it seems that some array functions are missing (!?). For example you can get the dom element this way:
    var elements = $(“div”);
    for(var i=0; i<elements.length; i++) { var element = elements[i]; }

    If you feel like peeking at the jquery object, run “console.dir($(“#myElement”));” in firebug.

  • Hari Karam Singh

    Are the elements of the array JQuery objects or native JS DOM ones?

  • Hari Karam Singh

    Are the elements of the array JQuery objects or native JS DOM ones?