2

How do I access or modify pseudo-selectors like :after and :hover of CSS of an element through JavaScript (please no jQuery).

Example

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Progress bar example</title>
        <style type="text/css">
        .progressbar
        {
            position: relative;
            width: 100px;
            height: 10px;
            background-color: red;
        }

        .progressbar:after
        {
            content: "";
            position: absolute;
            width: 25%;
            height: 100%;
            background-color: blue;
        }
        </style>
    </head>

    <body>
        <div id="progressbar" class="progressbar" onclick="this.style.width='90%';"></div>
    </body>
</html>

Like you see I want to use somethink like a progress bar, so I can't simply exchange/add/remove a second class to an element. I would like to access the the width property of the progressbar:after (with the :after selector) class directly through JS. But how?

StanE
  • 2,704
  • 29
  • 38

1 Answers1

0

You could give this a try:

EDITED

//create new style element
var style = document.createElement("style");

//append the style
document.head.appendChild(style);

//take the stylesheet object
sheet = style.sheet

//add the rule to your stylesheet -- changed this line to .insertRule
sheet.insertRule('.progressbar::after { width: 50% }', 0);

Updated fiddle

Ramiz Wachtler
  • 5,623
  • 2
  • 28
  • 33
  • Firefox 26's console tells me that addRule is not a function (doesn't FF 26 support it?). In all other browsers the the width value is applied to the main element, not the :after "element" (the entire div grows but not the blue bar inside). – StanE Nov 12 '14 at 02:17