2

As the title says, I'm trying to select some divs by their id, and then store them in an array, I know I can simply put the variables as parameters separated by comma, but I prefer to store. What I've done is:

var nationality = jQuery('#nationality');
var years = jQuery('#years');

var collection = [nationality, years];

jQuery('#mydiv').append(collection);

3 Answers 3

4

You can use add method:

var nationality = jQuery('#nationality');
var years = jQuery('#years');

var collection = nationality.add(years);

jQuery('#mydiv').append(collection);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for replying. What if I want to add more variables? Should I repeat the add method, or can I insert multiple parameters in it? I've tried inserting multiple, but with no success.
If you use add then you should chain it like this: $a.add($b).add($b), etc.
3

If you have an array, you must iterate the array and perform an action on each object found. This method will work below ->

var collection = new Array(nationality, years);
$.each(collection, function(i,v){
  //i = index, so 0,1,2,3,4,5
  //va = value, so <div id="1">1</div>', <div id="2">2</div>'; etc.
  jQuery('#mydiv').append(v);
});

1 Comment

Thanks for this answer, I like it more than the add method because it doesn't require chaining. But it is very hard to choose the 'answer' when both are the correct answers.
1

There is a little trick with apply():

$.fn.append.apply( $('#mydiv'), collection)

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.