What is the best way to replicate an HTML element's style properties in JavaScript or jQuery?

Is there a way to clone the style object of an element so that I can reset the styles back to their original values after making changes? Here's an example:

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.

I attempted to copy the style by assigning a variable to el.style, but that didn't work as any changes made to the style were reflected in the cloned object due to referencing. Then, I tried using jQuery's object extend method like this:

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

However, this method doesn't seem to be returning the expected results as curr_style.left is undefined.

If anyone has suggestions or solutions, please share! Your help would be greatly appreciated.

To retrieve each property, I ended up doing the following: (based on advice from @Raynos)

$.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;
};

Answer №1

let current_styles;
if (window.getComputedStyle) {
    current_styles = window.getComputedStyle(element);
} else if (element.currentStyle) {
    current_styles = $.extend(true, {}, element.currentStyle);
} else {
    throw "unsupported browser";
}

styles contains properties that are not enumerable, causing issues with .extend. It is recommended to use the getComputedStyle method to access an element's styles.

To ensure compatibility with older versions of Internet Explorer, consider extending element.currentStyle, which does have enumerable properties.

Setting the first argument to true instructs jQuery to perform a deep clone operation.

Answer №2

If you simply want to reset styles, I recommend using the cssText property of the style object. This method is supported in all major browsers and offers a straightforward solution.

Check out this example on jsFiddle:

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

Here's some sample code to demonstrate:

// Preserve the original style
var originalCssText = el.style.cssText;

// Modify a style property of the element
el.style.fontWeight = "bold";

// Reset the styles
el.style.cssText = originalCssText;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with disabled state in radio button container not functioning

I am facing an issue with a radio button div that I need to disable when the condition yAxisEditorCtrl.forceCombinedYAxis is true. Here is the original code: <div class="y-axis-editor"> <div class="vis-config-option display-size-normal form- ...

Order JSON data based on a predetermined list of keys using JavaScript

Imagine having a JSON list called LIST A: LIST A [ { "address": "wellington lane", "age": "23", "country": "Australia", "name": "Mike", "profession&q ...

JavaScript-Based Header Features Similar to Excel

Currently, I am in the process of developing a function that generates a sequence of strings similar to Excel headers. For those who may not be familiar with Excel, the sequence goes like this: A,B,...,Z,AA,...,AZ,BA,...,ZZ,AAA,...,etc. Here is the code ...

Discover the hidden truth: Unveiling the enigma of React

I'm currently learning React and I've been working on some apps to enhance my skills and deepen my understanding. Right now, I am facing a challenge where I need to incorporate the logged user information into the Redux state. However, whenever I ...

unable to import React Component

As I embark on creating a simple example React project, my goal is to utilize the npm package drag and drop file picker found at: https://www.npmjs.com/package/@yelysei/react-files-drag-and-drop To begin, I initiated a fresh React project using npx create ...

Guide on setting a v-model within a v-for loop (using an example from Bootstrap Vue)

Currently, I am utilizing vue-bootstrap for creating input fields using a v-for directive. The objective is quite similar to the example provided in this link. However, I am encountering some difficulties in obtaining the data collected from these inputs i ...

Javascript - Button animation malfunctioning after first click

One issue I'm facing is with an animation that is triggered using the onmousedown event. Another function is supposed to stop the animation when onmouseup is detected. The problem arises after the first time it works correctly. Subsequent attempts to ...

Changing the active state of an icon when clicked in a list generated by v-for in Vue

In my Vue.js application, I have created a list of objects where each object represents a star. I want to implement a feature where a star changes color when it is clicked. However, the issue I am facing is that when I click on one star, all the stars in ...

Using jQuery to dynamically pass variables to an HTML document

In my JavaScript file, I have the value 'testValue' stored. The code snippet below retrieves this value using a REST service and displays it in an input box: $('#testValue').val(RestServices.getValueCovid(response, 'TESTVALUE' ...

Perform the multiplication operation on two values retrieved from the API response and then calculate the total sum

I am currently pulling information from an API and I'm looking to perform a calculation on the data. Specifically, I want to multiply two different values from the response and then sum up the totals. While I already know how to sum all the values usi ...

What is the best way to initially conceal content and then reveal it only after an ajax call is made?

Currently, I have a situation where content is revealed after the callback function of a .js library (typed.js) executes. Here is the script I am using: Javascript $(function(){ $("#logo-black").typed({ strings: ["Nothing^450&Co^250.^500" ...

Looking to incorporate a raw JavaScript file into a React project

I have successfully converted my HTML and CSS components to React, but I am facing some challenges with the JS part. I attempted to use react-helmet, but encountered an error: Cannot read property 'addEventListener' of null Here is my React.js f ...

Utilizing Javascript to compile a variety of JSON objects from a JSON request

I am looking to convert a json request input into a specific format required by the backend using javascript. Can anyone suggest the best way or steps to achieve this? Any assistance will be highly appreciated! Thank you. The request input is as follows: ...

Easily create an HTML page from a multitude of intricate JavaScript objects with this convenient method

In my project, I am looking to dynamically generate an HTML page based on JavaScript objects and then present it to the user. For example: var mybutton = { id: 'button_1', x: '0', y: '0', width: '100', h ...

I encountered an issue with loading an array from session storage in Java Script

I am struggling to restore and reuse a created array in HTML. I attempted using JSON, but it was not successful for me. In the code below, I am attempting to reload items that were previously stored in an array on another page. However, when I try to loa ...

Is there a way for me to change a string into an array?

I have a question regarding string conversion. Here is a snippet of code from a CodeIgniter controller: function getUsersFromProjects(){ $projectID = $_POST['projectID']; $data = $this->tasks->getUserIdFromProjects($projectID); ...

Tips for preventing the first character of a word in the input box from being "-"

I'm looking for a solution to prevent the first character in a text box from being a "-" symbol. $(document).on("keypress", "#form_name", function() { if ($('#form_name').val().substr(0, 1) == "-") { return true } else { return ...

Collecting the timestamp when the page is loaded and then comparing it with the timestamp when the form is

I have implemented an anti-spam time trap in my application (although I realize its effectiveness may not be 100%, it serves as a temporary solution) that functions as follows: 1) Upon loading a page, a hidden input is populated with a timestamp using Jav ...

Struggling to access a remote URL through jQuery's getJSON function with jsonp, but encountering difficulties

Currently, I am attempting to utilize the NPPES API. All I need to do is send it a link like this and retrieve the results using jQuery. After my research, it seems that because it is cross-domain, I should use jsonp. However, I am facing difficulties m ...

Submitting information retrieved through an AJAX request to a MySQL database using PHP

I have implemented a JavaScript function to collect and display data, but now I am looking to save this data into a MySQL database for tracking purposes. I attempted to connect to the MySQL database locally using PHP code, but encountered some issues. I be ...