I want to create some DOM nodes with jQuery, append them to the html while keeping them selected, so I don’t need to select them again.
This is my code:
var foo=$('');
for(var i=0;i<10;i++){
var bar=$('<div>');
$('body').append(bar);
foo.add(bar);
}
Apparently foo will keep as empty in the end, so it’s not gonna work. How should I deal with it without selecting all the bars in the end?
The reason of this problem is
.add()method does not change the original jQuery collection object, but returns a new one.You could simply change your code to: The DEMO.