How to convert list of elements in an array using jQuery ?
Given an HTML document containing a list of elements and the task is to get the values of HTML list and convert it into an array using JavaScript.
Approach:
- Make a list(Ordered/ Unordered).
- Select the parent of <li> element and call an anonymous function for every child of parent( .each() or .map() methods ).
- Take the text value of each child and append that to the array.
Example 1: This example uses .each() method to convert a list of elements in an array.
<!DOCTYPE HTML>
< html >
< head >
< title >
How to convert list of elements
in an array using jQuery ?
</ title >
< script src =
</ script >
< style >
#ul {
width: 80px;
margin: 0 auto;
}
</ style >
</ head >
< body align = "center" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;" >
</ p >
< ul id = "ul" >
< li >GFG_1</ li >
< li >GFG_2</ li >
< li >GFG_3</ li >
</ ul >
< br >
< button onclick = "GFG_Fun()" >
click here
</ button >
< p id = "GFG_DOWN" style =
"font-size: 24px; font-weight: bold; color: green;" >
</ p >
< script >
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Click on the button to get "
+ "the values of list in array.";
function GFG_Fun() {
var arr = [];
$("ul li").each(function() { arr.push($(this).text())});
el_down.innerHTML = '"' + arr.join('", "') + '"';
}
</ script >
</ body >
</ html >
|
Output:
-
Before clicking on the button:
-
After clicking on the button:
Example 2: This example uses .map() method to convert a list of elements in an array.
<!DOCTYPE HTML>
< html >
< head >
< title >
How to convert list of elements
in an array using jQuery ?
</ title >
< script src =
</ script >
< style >
#ul {
width: 80px;
margin: 0 auto;
}
</ style >
</ head >
< body align = "center" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;" >
</ p >
< ul id = "ul" >
< li >GFG_1</ li >
< li >GFG_2</ li >
< li >GFG_3</ li >
</ ul >
< br >
< button onclick = "GFG_Fun()" >
click here
</ button >
< p id = "GFG_DOWN" style =
"font-size: 24px; font-weight: bold; color: green;" >
</ p >
< script >
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Click on the button to get "
+ "the values of list in array.";
function GFG_Fun() {
var arr = [];
arr = $('li').map(function(j, element) {
return $(element).text();
}).get();
el_down.innerHTML = '"' + arr.join('", "') + '"';
}
</ script >
</ body >
</ html >
|
Output:
-
Before clicking on the button:
-
After clicking on the button:
Last Updated :
05 Sep, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...