0

I want to pick all the elements inside the ul tag and push it in an array using javascript.How should I do that?

<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">Item 1</li>
<li class="ui-state-default">Item 2</li>
<li class="ui-state-default">Item 3</li>
<li class="ui-state-default">Item 4</li>
<li class="ui-state-default">Item 5</li>
</ul>
adeneo
  • 312,895
  • 29
  • 395
  • 388
user3767064
  • 11
  • 3
  • 7
  • 1
    Push what in an array, the element or just the text. The classname indicates that you're using jQuery, but it's not tagged with jQuery. – adeneo Jul 01 '14 at 09:09
  • Have you ever heard of the DOM? It seems like you would benefit the most from a tutorial which covers that: http://www.quirksmode.org/dom/intro.html – Felix Kling Jul 01 '14 at 09:11
  • the text only. Yes I am using jquery for this. But for the above problem even JS could do. – user3767064 Jul 01 '14 at 09:12
  • Please use the search before you ask a new question. – Felix Kling Jul 01 '14 at 09:17

4 Answers4

2

using .each() function on jQuery will help you achieve it.

try something like :

  var array = [];
    $( "li" ).each(function() {
      array.push($(this).text());
    });

for .each() reference click here

Yaje
  • 2,753
  • 18
  • 32
0
document.getElementById('sortable1').children

returns array-like object of li objects

Vlas Bashynskyi
  • 1,886
  • 2
  • 16
  • 25
0

Based on your class names, it looks like you are using jQuery...

var myItems = $("#sortable1").children();

Or, if you want the text only...

var myItems = [];

$("#sortable1").each(function() {
    var $this = $(this);
    myItems.push($this.text());
});
James Hill
  • 60,353
  • 20
  • 145
  • 161
0

JavaScript: DEMO

var sortable1 = document.getElementById("sortable1").children;
var array = new Array();
for(i=0; i<sortable1.length; i++) {
    array.push(sortable1[i].innerHTML);
}

jQuery: DEMO

var lis = $("#sortable1").children();
var array = new Array();
for(i=0; i<lis.length; i++) {
    array.push($(lis[i]).text());
}
MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89