Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store elements inside an array then use it later in jquery

var els = [];
els.push($("#something"));

I need to add this to the array because the properties of #something will be changed and I need to get it's original properties (height,width position etc.)

how do I now use the element inside els array?

like image 771
Gene Sy Avatar asked Jan 19 '26 10:01

Gene Sy


2 Answers

I would not store the entire object if there are only a few properties required.

$something = $('#something');
els[$something.attr('id')] = { 
  width: $something.width(),
  height: $something.height(),
  offset: $something.offset() };

console.log(els['something']);
like image 182
Christian Duvall Avatar answered Jan 20 '26 23:01

Christian Duvall


Well to use the saved jQuery object you'd just use normal array indexing:

els[0].css("backgroundColor", "purple");

Now, you say that you want to save that jQuery object to preserve its state. That won't work; the jQuery object is just a wrapper that provides access to the DOM element(s) chosen by your selector. It does not copy or preserve the state of the DOM, however. If the DOM changes, then those changes will be reflected by that jQuery object and old property values won't be available.

If you want to preserve the state of the element, you have to do it explicitly. For example, if "something" is an <input>, you could save its value:

var savedValue = $('#something').val();

If you want to save the properties to an array:

var els = [];
els.push({
  height: $('#something').height(),
  width: $('#something').width(),
  position: $('#something').position()
});

That'll push a whole new object (not a jQuery object; just a plain object with properties) to capture your DOM state.

Now you've got a copy of the "value" property, and subsequent DOM updates won't change that.

like image 22
Pointy Avatar answered Jan 21 '26 00:01

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!