0

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.

4 Answers 4

2

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

2 Comments

Wow... it works. But in the documentation I didn't see where it accepts an array of jQuery objects. I'm familiar with a jQuery-array being used here, but didn't realize a javascript array of jQuery would work the same.
jQuery actually seems to accept anything that has a length property everywhere it expects a jQuery object, and always wraps it. (You can create a jQuery object from an array: $([...]).
1

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);

Comments

1
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);

Comments

0

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);

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.