I normally store my jQuery objects in variables to avoid having the selector written all over the place.
When I change the DOM, I would like to make the object update itself. Dropping unused references and getting updated with the new ones. How can I do this? Ideally I want to do something with the following logic:
var test = $('div.bar');
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b2"></div>]
$('#b2').remove();
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b2"></div>]
test.update();
console.log(test);
>> [<div class="bar" id="b1"></div>]
$('body').append('<div class="bar" id="b3"></div>');
console.log(test);
>> [<div class="bar" id="b1"></div>]
test.update();
console.log(test);
>> [<div class="bar" id="b1"></div>, <div class="bar" id="b3"></div>]
This plugin solves that problem:
(function ( $ ) {
$.fn.update = function(){
var newElements = $(this.selector),i;
for(i=0;i<newElements.length;i++){
this[i] = newElements[i];
}
for(;i<this.length;i++){
this[i] = undefined;
}
this.length = newElements.length;
return this;
};
})(jQuery);
Just add it to your code and do:
var $foo = $("div.bar"); // selects all "div.bar"
(... many dom modifications ...)
$foo.update();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With