How to convert list of elements in an array using jQuery?

We can use jQuery.makeArray() method or jQuery.each() method to convert a list of elements into an array using jQuery. The makeArray() method is most convenient way to perform this task. This method is used to convert an object into a native array.

Using jQuery makeArray() method

The $.makeArray() method in jQuery converts an array-like object into a JavaScript array. It takes a single argument and convert it to array.

The following is syntax of $.makeArray() method-

$.makeArray(obj) 

Here obj is an object that we want to convert to an array.

Here are the steps we will follow.

  • Select the unordered list items using jQuery

  • Convert the list to an array using the makeArray method of jQuery

  • Map each item in the array to its innerHTML property

  • Now you got the array of elements and you can use it as a normal javascript array.

Example

In this example we are convertnt a list of elements into a array using $.makeArray( ) method if jQuery.


   


   

Convert list of elements in an array using jQuery

Click the following button to convert list of elements in an array


Given List

  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5

Array of list items:

Using jQuery each() Method

The each() method in jQuery is used to iterate arrays, objects, and all iterable items. To Convert list of elements in an array using jQuery we follow the steps given below

  • Select all the list items using $("ul li")

  • Create an empty array to store the list items

  • Loop through all the selected items using each() method

  • In each iteration, the innerText of the current list item is pushed into the "items" array.

  • Display the list items to the browser.

Example

In this example we are convertnt a list of elements into a array using $.each( ) method of Jquery.


   
 

   

Convert list of elements in an array using jQuery

Click the following button to convert list of elements in an array


Given List

  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5

Array of list items:

Updated on: 2023-02-21T16:59:26+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements