Get CSS from element, put in JSON-Array, change element, restore element with saved CSS array
So I want to get the css from a specific element, put it in a JSON array, change the element around, later restore the css of the element from the saved array.
I tried:
var currentCSS = $(this).css;
The result looks something like this:
function (a,c) if(arguments.length....
So it seems that this function is derived from jQuery, this is not what I want ...
I could iterate over the individual arguments I want, but there must be a better way ...
Then, in the end, I'll try something like:
$(this).css(currentCSS);
But there can be no elegant solution for this ...
source to share
If all you want is an inline style and not all of the style properties:
var $el=$(elem)
var style=$el.attr('style');
$el.removeAttr('style');
/* put style back*/
$el.attr('style',style);
Likewise, after you've processed it, remove any inline settings your code does ... removing the attribute style
should revert it to what was applied in the original css
source to share
Here's one way, but goodness is ugly. I don't think I have the wisdom to turn this into a plugin (but if someone else could be awesome! Please post a link!):
var elem = document.getElementById('a');
var originalCSSProperties = window.getComputedStyle(βelem,null);
var originalCSSValues = [];
for (var i=0,len=originalCSSProperties.length; i<len; i++){
originalCSSValues.push(
window
.getComputedStyle(elem,null)
.getPropertyValue(originalCSSProperties[i]));
}
$('#a').css({'background-color':'red','color':'black'});
$('#reset').click(
function(){
for (var c=0,leng=originalCSSProperties.length;c<leng;c++){
$('#a').css(originalCSSProperties[c],originalCSSValues[c]);
}
});
Since it depends window.getComputedStyle()
, it is absolutely not IE friendly, and while I haven't looked into compatibility yet, I suspect it might require fairly modern browsers in general. But, said, I hope this is helpful.
source to share
To start:
- Create a clone of your element with jQuery.clone and store it in a variable
- Remove children from clone
- Make the necessary changes to your item or its content.
If you want to go back to your original style
- Insert a clone before / after your element in the DOM
- Remove content from your element and add it to the clone
- Remove the element, leaving only cloning with your element's content.
Of course, there is no JSON array here where the styles are stored. Instead, your original styles are kept in a clone of your element. I think this will achieve the desired result anyway.
Here's the JSFiddle I showed it in action.
source to share