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?

3
  • This answer shows how to do something similar without jQuery (near the end). Commented Nov 12, 2014 at 1:51
  • He asked for an answer without JQuery, @eclipsis. Commented Nov 12, 2014 at 1:57
  • This seems to be related: stackoverflow.com/questions/1409225/… Commented Nov 14, 2014 at 1:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.