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
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 setelement.style
to an empty string ornull
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 theremoveAttribute
method. Here’s how you can do it in JavaScript:This code will remove the inline
style
attribute, which will effectively revert the element’s style back to what was defined in thestyle
attribute.Here’s a complete example:
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 thestyle
attribute.You can store the color in a const and reset it to the element whenever you want :
// Get the computed styles
const styles = window.getComputedStyle(element);
// Get the color property
// and later you can reset the color whenever you want: