Skip to content

Instantly share code, notes, and snippets.

@fmsf
Last active December 9, 2015 22:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fmsf/4340742 to your computer and use it in GitHub Desktop.
Save fmsf/4340742 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link
Author

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