How to clone an HTML element style object using JavaScript or jQuery?

I am trying to clone an element style object. This should allow me to reset the styles of the specified element after changing them.

For instance:

el.style.left; // 50px curr_style.left; // 50px; /* Modify the elements style. The cloned style should still hold the original properties from when it was cloned. */ el.style.left = '20px'; curr_style.left // should still return 50px. 

At first I tried to copy it by assigning the variable the value el.style. Unfortunately, this points to this by reference, and any style changes are reflected in the cloned object.

My other attempt was to use the jQuery object extension method to create a copy as such:

 var curr_style = $.extend( {}, el.style ); 

This does not work like curr_style.left etc. return undefined.

Any help would be appreciated!

I ended this to get each property: (based on @Raynos recommendations)

 $.fn.getStyle = function(){ var style, el = this[0]; // Fallbacks for old browsers. if (window.getComputedStyle) { style = window.getComputedStyle( el ); } else if (el.currentStyle) { style = $.extend(true, {}, el.currentStyle); } else { style = $.extend(true, {}, el.style); } // Loop through styles and get each property. Add to object. var styles = {}; for( var i=0; i<style.length; i++){ styles[ style[i] ] = style[ style[i] ]; } return styles; }; 
+6
source share
2 answers
 var curr_style; if (window.getComputedStyle) { curr_style = window.getComputedStyle(el); } else if (el.currentStyle) { curr_style = $.extend(true, {}, el.currentStyle); } else { throw "shit browser"; } 

style has non-enumerable properties that .extend . You want to use the getComputedStyle method to get the styles of an element.

You also want to support older versions of IE by extending el.currentStyle , which has enumerated properties.

The first argument (when set to true ) tells jQuery to make a deep clone.

+6
source

To simply reset styles, I would suggest just using the cssText (also see MDN ) of the style object. It works in all major browsers and is beautiful and simple.

jsFiddle:

http://jsfiddle.net/timdown/WpHme/

Code example:

 // Store the original style var originalCssText = el.style.cssText; // Change a style property of the element el.style.fontWeight = "bold"; // Now reset el.style.cssText = originalCssText; 
+4
source

Source: https://habr.com/ru/post/889610/


All Articles