skip to Main Content

I want to change back the style of a html element to its style="" parameter. I know that you change back an element style to its class, but is there any way to change back to its style="" in javascript? In another way, I’ve changed the style of it in javascript using element.style, and I basically want to be able to undo it and return it to be what it was after the style="", not the class, is this even possible and if it is, how do i do it?

I tried element.style.color = ""; and element.style.color = null; but they both just reset it to the text color in its class, where in its style="" the element color was changed to a different color, and i wanted it to change back to the color in its style.

2

Answers


  1. If you want to reset an HTML element’s style to what was defined in its style attribute (e.g., <div style="color: red;">), you can’t directly set element.style to an empty string or null to achieve that, because those will revert to the style defined in the element’s class or inherited styles.

    To revert to the inline style specified in the style attribute, you can use the removeAttribute method. Here’s how you can do it in JavaScript:

    // Assuming 'element' is the HTML element you want to reset
    element.removeAttribute("style");
    

    This code will remove the inline style attribute, which will effectively revert the element’s style back to what was defined in the style attribute.

    Here’s a complete example:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Reset Style to style=""</title>
    </head>
    <body>
        <div id="myElement" style="color: red; font-size: 18px;">This is some text.</div>
        <button onclick="resetStyle()">Reset Style</button>
    
        <script>
            function resetStyle() {
                const element = document.getElementById("myElement");
                element.removeAttribute("style");
            }
        </script>
    </body>
    </html>
    

    In this example, when you click the "Reset Style" button, it will remove the style attribute from the <div>, effectively reverting it to its original style defined in the style attribute.

    Login or Signup to reply.
  2. You can store the color in a const and reset it to the element whenever you want :

    const element = document.querySelector('#id');
    

    // Get the computed styles

    const styles = window.getComputedStyle(element);

    // Get the color property

    const color = styles.getPropertyValue('color');
    element.style.color = "green";
    

    // and later you can reset the color whenever you want:

    element.style.color = color;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search