aw crud
aw crud

Reputation: 8891

How can I replace one DOM element with an array of jQuery objects?

I have an array of jQuery objects that I built and which have events attached to them.

var obs = [];
for(var i=0;i<100;i++) {
  var j = jQuery('<div></div>');
  j.click(function() { console.log('Clicked ' + i); });
  obs.push(j);
}

My HTML is:

<div id="replaceme"></div>

How do I replace the div on the page with all the jQuery objects in my array? I don't want to concatenate their HTML because I want to preserve the event handlers.

Upvotes: 0

Views: 992

Answers (4)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99921

You can replace an element with an array of jQuery elements by doing this:

$(theElement).replaceWith(theArryaOfjQueryElements);

In your case, this is:

$('#replaceme').replaceWith(objs);

See the jQuery.replaceWith() method.


BTW you have an error here:

j.click(function() { console.log('Clicked ' + i); });

This will always print Clicked 100. The reason is that your function closes a reference to i, not to it's value. So if i is modified before this function is called, the function will see the new value of i.

You should do this instead:

 (function(i) {
     j.click(function() { console.log('Clicked ' + i); });
 }(i));

Upvotes: 2

Wulf
Wulf

Reputation: 3898

I read, that creating all elements at once is much faster then creating one by one. With the click function, you could count all previous siblings to get the index:

var str = ''
for (var i = 0; i < 100; i++) {
  str += '<div></div>';
}
var elem = jQuery(str);
elem.click(function() { console.log('clicked '+jQuery(this).prevAll().length); });

jQuery('#replaceme').replaceWith(elem);

Upvotes: 0

Seth
Seth

Reputation: 6260

var obs = [];
for(var i=0;i<100;i++) {
    var j = jQuery('<div></div>');
    j.click(function() { console.log('Clicked ' + i); });
    obs.push(j);
}

$('#replaceme').html(objs);
/* or */
$('#replaceme').replaceWith(objs);

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69915

Use replaceWith jQuery method which replaces each element in the set of matched elements with the provided new content.

var $obj = jQuery();//This will create an empty jQuery object
for(var i=0;i<100;i++) {
  var j = jQuery('<div></div>');
  j.click(function() { console.log('Clicked ' + i); });
  $obj.add(j);//Using add method to add the jQuery object into $obj
}

$("#replaceme").replaceWith($obj);

Upvotes: 1

Related Questions