0

I want to save selected items to an array.

for example:

 var list = $('ul.theList li'),
           result = $('div#result'); // other div
           content;

 for( var i=0; i < list.length; i++ ){
       content[i] = $('ul.theList li')[i];
 }

 $(result).text(content); // the result

This doesnt work.

1
  • content=[] you are missing the initialisation Commented Nov 17, 2012 at 15:31

2 Answers 2

1

There's two issues, first you've not defined the content as an array, and with that code you should probably define how the array-elements should be joined:

 var list = $('ul.theList li'),
           result = $('div#result'),
           content = [];

 for( var i=0; i < list.length; i++ ){
       content.push($('ul.theList li:eq(' + i + ')').text());
       /* or:
       content.push($('ul.theList li').eq(i).text());
       */
 }

 $(result).text(content.join(', '));

JS Fiddle demo using :eq() selector.

JS Fiddle demo using .eq() method.

I've used .push() to insert the text of the li (I'm assuming, here, that you want the text and not the node itself) to the content array, rather than explicitly defining the index.

References:

Sign up to request clarification or add additional context in comments.

Comments

1

Better use jQuery now you have it

version 1

var list = $('ul.theList li'),

$('#result').text(list.text());

version 2

var list = $('ul.theList li');
list.each(function(i) {
  $('#result').append(i+".: "+$(this).text()+"<br/>");
});

1 Comment

So why not accept mine? I did not bother post the eq(i) because it was not necessary.

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.