1

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!

2 Answers 2

9

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());
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I wanted to find out how to create the array from the contents and not the entire li DOM elements
4
$('li').map(function() { 
  return $(this).val();
}).get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.