Harry Gilmore
Harry Gilmore

Reputation: 11

When you modify a jQuery collection within an each loop, is the modified collection included or just the original?

When you modify a jQuery collection within an each loop, is the modified collection included or just the original?

For example

var collection = $("div");
$(collection).each(function(){
    var originalDiv = $(this);
    var cloneDiv = $(this).clone();
    cloneDiv.insertAfter(originalDiv);
});

Are the clone divs now included in the loop or is it only the original collection?

Upvotes: 0

Views: 92

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073978

The jQuery object in collection is unaffected by the clone and insertAfter calls you're doing in the loop. jQuery objects are snapshots (like the ones you get from querySelectorAll), not live collections (like the ones you get from getElementsByTagName or getElementsByClassName or similar), and neither clone nor insertAfter adds it to collection.

You can easily prove this to yourself:

// Your code (without the unnecessary `$()` around `collection`
var collection = $("div");
collection.each(function(){
    var originalDiv = $(this);
    var cloneDiv = $(this).clone();
    cloneDiv.insertAfter(originalDiv);
});

// Now, do another operation on the contents of `collection` -- notice how only
// the original contents are affected, not the divs created during the loop
collection.css("color", "blue");
<div>a</div>
<div>b</div>
<div>c</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Even if you were using one of the methods to add the element to a jQuery object, in general, jQuery methods create new jQuery objects rather than modifying the state of the jQuery object you call them on. (I think there are exceptions to that rule, but one doesn't immediately come to mind.) For instance, you can "add" an element by calling add, but it doesn't change the jQuery object you call it on; instead, it creates and returns a new jQuery object containing the original elements and the new one.

Upvotes: 0

Related Questions