Henry Yun
Henry Yun

Reputation: 544

How can jQuery convert my ordered list into an array?

This is my list:

<ol>
    <li>Audi</li>
    <li>Kawasaki</li>
    <li>Vauxhall</li>
</ol>

What is the jQuery function that will transform the list items into an array?

var cars;
$('li').map(function() {
    // converts the ordered list into a javascript array named 'cars'
}); 

Thanks!

Upvotes: 1

Views: 12932

Answers (2)

leeny
leeny

Reputation: 626

$('li').map(function() { 
  return $(this).val();
}).get();

Upvotes: 4

maid450
maid450

Reputation: 7486

If what you want is an array of the li DOM elements you can just use jQuery's toArray():

var cars = $('li').toArray();

If what you need is an array containing ['audi', 'kawasaki',...] then:

var cars = [];
$('li').each(function(i, elem) {
    cars.push($(elem).text());
});

Upvotes: 9

Related Questions