• jQuery Video Tutorials

jQuery Misc toArray() Method



Syntax

The jQuery toArray() method converts a jQuery object into a plain array of DOM elements. It returns an array containing all the DOM elements in the jQuery object.

$(selector).toArray()

Example

In the following example, we are using the jQuery toArray() method convert the <li> elements to an array −

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
      $("#displayItems").click(function(){
        var itemsArray = $("li").toArray();
        var listContainer = $("<div></div>");
        
        itemsArray.forEach(function(item, index) {
          var listItem = $("<p></p>").text((index + 1) + ". " + $(item).text());
          listContainer.append(listItem);
        });

        $("#output").html(listContainer);
      });
    });
  </script>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }
    #output p {
      font-weight: bold;
      color: #333;
    }
  </style>
</head>
<body>

<h2>List of Beverages</h2>
<button id="displayItems">Show List Items</button>

<ul>
  <li>Coffee</li>
  <li>Milk</li>
  <li>Soda</li>
</ul>

<div id="output"></div>

</body>
</html>

After executing, click on the button to retrieve all the elements from the array.

jquery_ref_miscellaneous.htm
Advertisements