Create a gist now

Instantly share code, notes, and snippets.

Mini jquery plugin to update a stored jQuery object based on the original selector string. It will effectively replace all previous dom nodes with the ones matched when the update function is called;
(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);
// usage
var $foo = $("div.bar"); // selects current elements
(... many dom modifications ..)
$foo.update(); // updates with all new "div.bar" elements present in the dom, and removes those no longer present.
@fmsf
Owner
fmsf commented Dec 19, 2012

I normally store jQuery objects in variables to avoid having selector strings or references to strings all over the place, while also caching selectors. The issue is that after doing DOM modifications the jQuery object is an invalid representation and needs an update. This plugin fixes that.

@fmsf
Owner
fmsf commented Feb 8, 2013

I've migrated this to a normal git repository: https://github.com/fmsf/jQuery-obj-update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment