I ran yesterday in a problem with a jquery-selector I assigned to a variable and it's driving me mad.
Here is a jsfiddle with testcase:
Another test: Adding a li element to the domtree and logging obj and .elem. .elem does have the new li and obj doesn't, because it's still the old snapshot
http://jsfiddle.net/CBDUK/1/
Is there no way to update this obj with the new content? I don't want to make a new obj, because in my application there is a lot information saved in that object, I don't want to destroy...
refresh = function() { return $(this. selector); }; var a = $(". elem"); a = a. refresh();
ID and Element selector are the fastest selectors in jQuery.
Projects In JavaScript & JQueryYes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.
Caching enhances the performance of the application. Cache your jQuery selectors for better performance. This can be done using the ID as your selector. For example, this caches the selector and stores it in variable.
Yeah, it's a snapshot. Furthermore, removing an element from the page DOM tree isn't magically going to vanish all references to the element.
You can refresh it like so:
var a = $(".elem"); a = $(a.selector);
Mini-plugin:
$.fn.refresh = function() { return $(this.selector); }; var a = $(".elem"); a = a.refresh();
This simple solution doesn't work with complex traversals though. You are going to have to make a parser for the .selector
property to refresh the snapshot for those.
The format is like:
$("body").find("div").next(".sibling").prevAll().siblings().selector //"body div.next(.sibling).prevAll().siblings()"
In-place mini-plugin:
$.fn.refresh = function() { var elems = $(this.selector); this.splice(0, this.length); this.push.apply( this, elems ); return this; }; var a = $(".elem"); a.refresh() //No assignment necessary
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