Search code examples
htmlcssstyles

How to remove style from <html>


I want to remove the style attribute from html: <html style="">

For example:

<html style="--athens-gray:#121212; --alabaster:#1E1E1E; --black:#ffffff; --white:#000000;">

Should be <html>.

This is my script:

const themes = {
  dark: {
      '--white': '#000000',
  },
  light: {
      '--white': '#ffffff',
  },
};
function lighttheme() {
const theme = themes["dark"];
    for (var variable in theme) {
            document.documentElement.style.setProperty(variable, theme[variable]);
    };
}
:root {
  --athens-gray: #e9e8ec;
  --alabaster: #f8f8f8;
  --black: #000000;
  --white: #ffffff;
}

body {
background-color: var(--white);
}
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Settings</title>
    </head>
<body>
<button type="button" onClick="lighttheme();">Click Me!</button>
</body>
</html>


Solution

  • You can do that by this code:

    document.getElementsByTagName("html")[0].removeAttribute("style")

    For example:

    const themes = {
      dark: {
          '--athens-gray': '#121212',
          '--alabaster': '#1E1E1E',
          '--black': '#ffffff',
          '--white': '#000000',
      },
      light: {
          '--athens-gray': '#e9e8ec',
          '--alabaster': '#f8f8f8',
          '--black': '#000000',
          '--white': '#ffffff',
      },
    };
    function lighttheme() {
    const theme = themes["dark"];
        for (var variable in theme) {
                document.documentElement.style.setProperty(variable, theme[variable]);
        };
    }
    
    function removeStyle(){
        document.getElementsByTagName("html")[0].removeAttribute("style");
    }
    :root {
      --athens-gray: #e9e8ec;
      --alabaster: #f8f8f8;
      --black: #000000;
      --white: #ffffff;
    }
    
    body {
    background-color: var(--white);
    }
    <!doctype html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Settings</title>
        </head>
    <body>
    <button type="button" onClick="lighttheme();">Click Me!</button>
    <button type="button" onClick="removeStyle()">Remove Style!</button>
    </body>
    </html>

    If I comment javascript code you will see the page's color gets red.