skip to Main Content

window.getComputedStyle gives us all CSS rules applied to an element. I want to get only user-defined styles with JavaScript or CSS, whether they are inline, in a separate file, or inside a style tag. And ignore browsers default styles

2

Answers


  1. If you do not use CSS rules applied to elements directly, You can compare the output of the DIV (or other element) in question with a newly created element with browser defaults.

    window.getComputedStyle(document.createElement("div"))
    

    If you use these (anyway not recommended) it will not work

    div {
    color:blue;
    }
    
    Login or Signup to reply.
  2. This is not realistic to do. Because, for example, set color will overwrite a number of properties by default except for color. Look at this example:

    const div = document.createElement('div');
    document.body.append(div);
    const browserStyles = window.getComputedStyle(div);
    
    const myDivStyles = window.getComputedStyle(myDiv);
    
    const styles = {};
    
    for (const prop in browserStyles) {
      if (browserStyles[prop] !== myDivStyles[prop]) {
        styles[prop] = myDivStyles[prop];
      }
    }
    
    console.log(styles);
    <div id="myDiv" style="color: red;"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search