Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a jQuery object stored in a variable after DOM change?

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>]
like image 357
fmsf Avatar asked Dec 30 '12 11:12

fmsf


1 Answers

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();
like image 84
fmsf Avatar answered Nov 07 '22 00:11

fmsf