Is there any way to select/manipulate CSS pseudo-elements such as ::before and ::after (and the old version with one semi-colon) using jQuery?

For example, my stylesheet has the following rule:

.span::after{ content:'foo' }

How can I change 'foo' to 'bar' using jQuery?

1 upvote
  flag
4 upvote
  flag
I made something that should work for you: gist.github.com/yckart/5563717 – yckart
1 upvote
  flag
I hate such comments on stackoverflow that I'm going to write (where commenter asks why don't you do it some complete opposite way?), but: at some point one should realize code-design issue and replace that pseudo element with a span or something. I guess you know what I'm pointing at. – zsitro
upvote
  flag
Accepted answer is excellent. Though if you are trying to achieve any of the following points, the answer wont work: 1. change style of :before by JS. 2. change content of :before by JS Please see my answer for that if you need it. – Learner
upvote
  flag

18 Answers 11

Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, and thus you can't select and manipulate them directly with jQuery (or any JavaScript APIs for that matter, not even the Selectors API).

You can always find other ways around it, though, for example:

  • Applying the styles to the pseudo-elements of one or more arbitrary classes, then toggling between classes using jQuery (see seucolega's answer for a quick example) — this is the idiomatic way as it makes use of simple selectors (which pseudo-elements are not) to distinguish between elements and element states, the way they're intended to be used

  • Manipulating the styles being applied to said pseudo-elements, by altering the document stylesheet, which is much more of a hack

But you still can't access them directly as ultimately they're only visible to the rendering engine, and not available through any scripting APIs (except possibly the CSSOM, which is not exposed by jQuery beyond .css() which only works for actual elements and not pseudo-elements either).

This applies to any pseudo-elements whose styles you're trying to modify with jQuery, and not just :before and :after.

You can't select pseudo elements in jQuery because they are not part of DOM. But you can add an specific class to the father element and control its pseudo elements in CSS.

EXAMPLE

In jQuery:

<script type="text/javascript">
    $('span').addClass('change');
</script>

In CSS:

span.change:after { content: 'bar' }
up vote 572 down vote accepted

You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:

In HTML:

<span>foo</span>

In jQuery:

$('span').hover(function(){
    $(this).attr('data-content','bar');
});

In CSS:

span:after {
    content: attr(data-content) ' any other text you may want';
}

If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:

In HTML:

<span>foo</span>

In jQuery:

$('span').hover(function(){
    $(this).addClass('change').attr('data-content','bar');
});

In CSS:

span.change:after {
    content: attr(data-content) ' any other text you may want';
}
2 upvote
  flag
Do you have a link in the spec for using that attr function against the content property? I'm surprised I've never heard of this... – Kevin Peno
5 upvote
  flag
75 upvote
  flag
+1 for attr(), too bad i wasn't able to use it with other properties than content. Demo – Maksim Vi.
22 upvote
  flag
That's because no browser in existence has implemented attr() beyond CSS2 yet, whereas in CSS2 itself attr() has only been defined for the content property. – BoltClock
upvote
  flag
This does not work for image urls like background-image: url( attr(data-image, url) ); – chovy
upvote
  flag
@chovy: See my comment for the reason why. – BoltClock
upvote
  flag
How could I use this to pass an img url ? : .attr("data-content",url('../images/loader.gif')); – Jk_
8 upvote
  flag
Updated link for Attribute References: w3.org/TR/css3-values/#attr-notation – user166560
upvote
  flag
hmm this won't work if you want to change other properties of the pseudo element such as margin via a jQuery animation. – Sumit
upvote
  flag
@chofy @Sumit That's true; you can currently only use attr() in CSS to read simple strings for the content property. – Blazemonger
upvote
  flag
Does anyone know the browser compatibility for this? I assume this won't work for certain versions of IE. – Johannes
3 upvote
  flag

one working but not very efficient way is to add a rule to the document with the new content and reference it with a class. depending on what is needed the class might need an unique id for each value in content.

$("<style type='text/css'>span.id-after:after{content:bar;}</style>").appendTo($("head"));
$('span').addClass('id-after');

In the line of what Christian suggests, you could also do:

$('head').append("<style>.span::after{ content:'bar' }</style>");
upvote
  flag
That's a really nice solution to change the style as well! – pmrotule
2 upvote
  flag
Here should be added an id-attribute, so the element can be selected and deleted before a new one is added. If not, there can come up a lot of unnecessary style-nodes. – K.S.

I've answered this question here already, but to be super-cool I'll repeat myself for you.

The answer should be Yes & No. You can not select an element via pseudo-selector, but you can add a new rule to your stylesheet with javascript.

I made something that should work for you:

var addRule = function(sheet, selector, styles) {
    if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
    if (sheet.addRule) return sheet.addRule(selector, styles);
};

addRule(document.styleSheets[0], "body:after", "content: 'foo'");

http://fiddle.jshell.net/MDyxg/1/

2 upvote
  flag
It's not cool to copy and paste the same answer across multiple questions. You should flag the other question as a duplicate instead. Also, what is Jain? – BoltClock
upvote
  flag
Ok, I've to accept! :) – yckart

You'd think this would be a simple question to answer, with everything else that jQuery can do. Unfortunately, the problem comes down to a technical issue: css :after and :before rules aren't part of the DOM, and therefore can't be altered using jQuery's DOM methods.

There are ways to manipulate these elements using JavaScript and/or CSS workarounds; which one you use depends on your exact requirements.


I'm going to start with what's widely considered the "best" approach:

1) Add/remove a predetermined class

In this approach, you've already created a class in your CSS with a different :after or :before style. Place this "new" class later in your stylesheet to make sure it overrides:

p:before {
    content: "foo";
}
p.special:before {
    content: "bar";
}

Then you can easily add or remove this class using jQuery (or vanilla JavaScript):

$('p').on('click', function() {
    $(this).toggleClass('special');
});

    $('p').on('click', function() {
      $(this).toggleClass('special');
    });
p:before {
  content: "foo";
  color: red;
  cursor: pointer;
}
p.special:before {
  content: "bar";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

  • Pros: Easy to implement with jQuery; quickly alters multiple styles at once; enforces separation of concerns (isolating your CSS and JS from your HTML)
  • Cons: CSS must be pre-written, so the content of :before or :after isn't completely dynamic

2) Add new styles directly to the document's stylesheet

It's possible to use JavaScript to add styles directly to the document stylesheet, including :after and :before styles. jQuery doesn't provide a convenient shortcut, but fortunately the JS isn't that complicated:

var str = "bar";
document.styleSheets[0].addRule('p.special:before','content: "'+str+'";');

var str = "bar";
document.styleSheets[0].addRule('p.special:before', 'content: "' + str + '";');
p:before {
  content: "foo";
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>

.addRule() and the related .insertRule() methods are fairly well-supported today.

As a variation, you can also use jQuery to add an entirely new stylesheet to the document, but the necessary code isn't any cleaner:

var str = "bar";
$('<style>p.special:before{content:"'+str+'"}</style>').appendTo('head');

var str = "bar";
$('<style>p.special:before{content:"' + str + '"}</style>').appendTo('head');
p:before {
  content: "foo";
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>

If we're talking about "manipulating" the values, not just adding to them, we can also read the existing :after or :before styles using a different approach:

var str = window.getComputedStyle(document.querySelector('p'), ':before') 
           .getPropertyValue('content');

var str = window.getComputedStyle($('p')[0], ':before').getPropertyValue('content');
console.log(str);

document.styleSheets[0].addRule('p.special:before', 'content: "' + str+str + '";');
p:before {
    content:"foo";
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p class="special">This is a paragraph</p>
<p>This is another paragraph</p>

We can replace document.querySelector('p') with $('p')[0] when using jQuery, for slightly shorter code.

  • Pros: any string can be dynamically inserted into the style
  • Cons: original styles aren't altered, just overridden; repeated (ab)use can make the DOM grow arbitrarily large

3) Alter a different DOM attribute

You can also to use attr() in your CSS to read a particular DOM attribute. (If a browser supports :before, it supports attr() as well.) By combining this with content: in some carefully-prepared CSS, we can change the content (but not other properties, like margin or color) of :before and :after dynamically:

p:before {
    content: attr(data-before);
    color: red;
    cursor: pointer;
}

JS:

$('p').on('click', function () {
    $(this).attr('data-before','bar');
});

$('p').on('click', function () {
    $(this).attr('data-before','bar');
});
p:before {
    content: attr(data-before);
    color: red;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

This can be combined with the second technique if the CSS can't be prepared ahead of time:

var str = "bar";

document.styleSheets[0].addRule('p:before', 'content: attr(data-before);');

$('p').on('click', function () {
    $(this).attr('data-before', str);
});

var str = "bar";
document.styleSheets[0].addRule('p:before', 'content: attr(data-before) !important;');

$('p').on('click', function() {
  $(this).attr('data-before', str);
});
p:before {
  content: "foo";
  color: red;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

  • Pros: Doesn't create endless extra styles
  • Cons: attr in CSS can only apply to content strings, not URLs or RGB colors
1 upvote
  flag
I'm trying to dynamically set glyphicon values (i.e., via their hex values) in ::after psedo. content: element (e.g., content: "\e043";). it doesn't seem to work for me so I'm assuming it doesn't work for hex values for glyphicons either? – user2101068
upvote
  flag
@user2101068 You should post that as a new question. I'd have to see all the code you're using. – Blazemonger
upvote
  flag
Blazemonger, thanks for the quick reply..unfortunately there is a quite a bit of code and it would take quite a bit of effort to snip out the relevant code. I've already spent 12+ hours trying to get this work and this was my last gasp effort to get it to work. I need to cut my losses. I was hoping you might be able to just verify my assumption re: hex values when using the technique you described in #3 above (before code snippet). I can insert hex string in content element but it displays text for glyphicon hex value rather than the actual glyphicon. Impression without seeing all code? – user2101068
upvote
  flag
@user2101068 Don't use the hex string; instead, copy and paste the actual Unicode character into the HTML attribute. jsfiddle.net/mblase75/Lcsjkc5y – Blazemonger
upvote
  flag
regarding solution 2. & 3. actually you can prevent stylesheet from (over)growing if you use: document.styleSheets[0].insertRule(rule, index), then using this index you can remove the rules when not needed: document.styleSheets[0].deleteRule(index) – Picard

Here is the HTML:

<div class="icon">
  <span class="play">
    ::before
  </span>
</div>

Computed style on 'before' was content: "VERIFY TO WATCH";

Here is my two lines of jQuery, which use the idea of adding an extra class to specifically reference this element and then appending a style tag (with an !important tag) to changes the CSS of the sudo-element's content value:

$("span.play:eq(0)").addClass('G');

$('body').append("<style>.G:before{content:'NewText' !important}</style>");

IF you want to to manipulate the ::before or ::after sudo elements entirely through CSS, you could do it JS. See below;

jQuery('head').append('<style id="mystyle" type="text/css"> /* your styles here */ </style>');

Notice how the <style> element has an ID, which you can use to remove it and append to it again if your style changes dynamically.

This way, your element is style exactly how you want it through CSS, with the help of JS.

1 upvote
  flag
this is very cool for another reason: if one's building a jquery plugin and doesn't want to require the inclusion of a stylesheet but needs to predefine certain styles, this is a great way to do it! – ekkis

Thank you all! i managed to do what i wanted :D http://jsfiddle.net/Tfc9j/42/ here take a look

i wanted to have the opacity of an outer div to be different from the opacity of the internal div and that change with a click somwewhere ;) Thanks!

   $('#ena').on('click', function () {
        $('head').append("<style>#ena:before { opacity:0.3; }</style>");
    });

$('#duop').on('click', function (e) {

        $('head').append("<style>#ena:before { opacity:0.8; }</style>");

     e.stopPropagation(); 
    });

#ena{
    width:300px;
    height:300px;
    border:1px black solid;
    position:relative;
}
#duo{
    opacity:1;
    position:absolute;
    top:50px;
  width:300px;
    height:100px;
      background-color:white;
}
#ena:before {
    content: attr(data-before);
    color: white;
    cursor: pointer;
    position: absolute;
    background-color:red;
    opacity:0.9;
    width:100%;
    height:100%;
}


<div id="ena">
    <div id="duo">
        <p>ena p</p>
        <p id="duop">duoyyyyyyyyyyyyyy p</p>

    </div>   


</div>
upvote
  flag
Not try append, use html is best prevent – KingRider
upvote
  flag
+1. This is exactly what I was searching for, to change the opacity of a div. The other answers are very thorough, but they all focused on adding styles, not modifying existing ones. Thank you! – scott
upvote
  flag
Watch out: here you are appending a style tag to the head every time one of those clicks is handled. I'd code a way to remove the old one before adding a new one. – pupitetris

Here is the way to access :after and :before style properties, defined in css:

// Get the color value of .element:before
var color = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('color');

// Get the content value of .element:before
var content = window.getComputedStyle(
    document.querySelector('.element'), ':before'
).getPropertyValue('content');
upvote
  flag
Impossible make setProperty? i try not work. – KingRider

You may create a fake property or use an existing one and inherit it in the pseudo-element's stylesheet.

var switched = false;

// Enable color switching
setInterval(function () {
    var color = switched ? 'red' : 'darkred';
    var element = document.getElementById('arrow');
    element.style.backgroundColor = color;
    
    // Managing pseudo-element's css
    // using inheritance.
    element.style.borderLeftColor = color;
    
    switched = !switched;
}, 1000);
.arrow {
    /* SET FICTIONAL PROPERTY */
    border-left-color:red;
    
    background-color:red;
    width:1em;
    height:1em;
    display:inline-block;
    position:relative;
}
.arrow:after {
    border-top:1em solid transparent;
    border-right:1em solid transparent;
    border-bottom:1em solid transparent;
    border-left:1em solid transparent;
    
    /* INHERIT PROPERTY */
    border-left-color:inherit;
    
    content:"";
    width:0;
    height:0;
    position:absolute;
    left:100%;
    top:-50%;
}
<span id="arrow" class="arrow"></span>

It seems it doesn't work for "content" property :(

This is not practical as i did not write this for real world uses, just to give you a example of what can be achieved.

css = {
before: function(elem,attr){ 

if($("#cust_style") !== undefined){ 
$("body").append("<style> " + elem + ":before {"  + attr +  "} </style>"); 
} else {
 $("#cust_style").remove();
$("body").append("<style> " + elem + ":before {"  + attr +  "} </style>"); 
}

}, after: function(elem,attr){
if($("#cust_style") !== undefined){ 
$("body").append("<style> " + elem + ":after {"  + attr +  "} </style>"); 

} else { $("#cust_style").remove();
$("body").append("<style> " + elem + ":after {"  + attr +  "} </style>"); 
}
}
}

this currently add's a / or appends a Style element which contains your necessary attribute's which will take affect on the target element's after Pseudo element.

this can be used as

css.after("someElement"," content: 'Test'; position: 'absolute'; ") // editing / adding styles to :after

and

css.before( ... ); // to affect the before pseudo element.

as after: and before: pseudo elements are not directly accessible through DOM it is currently not possible to edit the Specific values of the css freely.

my way was just a example and its not good for practice, you can modify it try some of your own tricks and make it correct for real world usage.

so do your own experimentation's with this and others!

regards - Adarsh Hegde.

Why adding classes or attributes when you can just append a style to head

$('head').append('<style>.span:after{ content:'changed content' }</style>')

There are many answers here but no answer helps to manipulate the css of :before or :after , not even the accepted one.

Here is how I propose to do it. Lets suppose your HTML is like this:

<div id="something">Test</div>

And then you are setting its :before in CSS and designing it like:

#something:before{
   content:"1st";
   font-size:20px;
   color:red;
}
#something{
  content:'1st';
}

Please notice I also set content attribute in element itself so that you can take it out easily later. Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:

Define a css with your required style on some class .activeS :

.activeS:before{
   color:green !important;
   font-size:30px !important;
 }

Now you can change :before style by adding the class to your :before element as follows:

<button id="changeBefore">Change</button>
<script>
    $('#changeBefore').click(function(){
        $('#something').addClass('activeS');
    });
</script>

If you just want to get content of :before, it can be done as:

<button id="getContent">Get Content</button>
<script>
    $('#getContent').click(function(){
        console.log($('#something').css('content'));//will print '1st'
    });
</script>

Ultimately if you want to dynamically change :before content by jQuery, You can achieve that as follows:

<button id="changeBefore">Change</button>
<script>
    var newValue = '22';//coming from somewhere
    var add = '<style>#something:before{content:"'+newValue+'"!important;}</style>';
    $('#changeBefore').click(function(){
        $('body').append(add);
    });
</script>

Clicking on above "changeBefore" button will change :before content of #something into '22' which is a dynamic value.

I hope it helps

 $('.span').attr('data-txt', 'foo');
        $('.span').click(function () {
         $(this).attr('data-txt',"any other text");
        })
.span{
}
.span:after{ 
  content: attr(data-txt);
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='span'></div>

You can use my plugin for this purpose.

JQuery:

(function() {
  $.pseudoElements = {
    length: 0
  };

  var setPseudoElement = function(parameters) {
    if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {
      for (var element of parameters.elements.get()) {
        if (!element.pseudoElements) element.pseudoElements = {
          styleSheet: null,
          before: {
            index: null,
            properties: null
          },
          after: {
            index: null,
            properties: null
          },
          id: null
        };

        var selector = (function() {
          if (element.pseudoElements.id !== null) {
            if (Number(element.getAttribute('data-pe--id')) !== element.pseudoElements.id) element.setAttribute('data-pe--id', element.pseudoElements.id);
            return '[data-pe--id="' + element.pseudoElements.id + '"]::' + parameters.pseudoElement;
          } else {
            var id = $.pseudoElements.length;
            $.pseudoElements.length++

              element.pseudoElements.id = id;
            element.setAttribute('data-pe--id', id);

            return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;
          };
        })();

        if (!element.pseudoElements.styleSheet) {
          if (document.styleSheets[0]) {
            element.pseudoElements.styleSheet = document.styleSheets[0];
          } else {
            var styleSheet = document.createElement('style');

            document.head.appendChild(styleSheet);
            element.pseudoElements.styleSheet = styleSheet.sheet;
          };
        };

        if (element.pseudoElements[parameters.pseudoElement].properties && element.pseudoElements[parameters.pseudoElement].index) {
          element.pseudoElements.styleSheet.deleteRule(element.pseudoElements[parameters.pseudoElement].index);
        };

        if (typeof parameters.argument === 'object') {
          parameters.argument = $.extend({}, parameters.argument);

          if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {
            var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;

            element.pseudoElements[parameters.pseudoElement].index = newIndex;
            element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;
          };

          var properties = '';

          for (var property in parameters.argument) {
            if (typeof parameters.argument[property] === 'function')
              element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();
            else
              element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];
          };

          for (var property in element.pseudoElements[parameters.pseudoElement].properties) {
            properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
          };

          element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);
        } else if (parameters.argument !== undefined && parameters.property !== undefined) {
          if (!element.pseudoElements[parameters.pseudoElement].properties && !element.pseudoElements[parameters.pseudoElement].index) {
            var newIndex = element.pseudoElements.styleSheet.rules.length || element.pseudoElements.styleSheet.cssRules.length || element.pseudoElements.styleSheet.length;

            element.pseudoElements[parameters.pseudoElement].index = newIndex;
            element.pseudoElements[parameters.pseudoElement].properties = {};
          };

          if (typeof parameters.property === 'function')
            element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();
          else
            element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;

          var properties = '';

          for (var property in element.pseudoElements[parameters.pseudoElement].properties) {
            properties += property + ': ' + element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
          };

          element.pseudoElements.styleSheet.addRule(selector, properties, element.pseudoElements[parameters.pseudoElement].index);
        };
      };

      return $(parameters.elements);
    } else if (parameters.argument !== undefined && parameters.property === undefined) {
      var element = $(parameters.elements).get(0);

      var windowStyle = window.getComputedStyle(
        element, '::' + parameters.pseudoElement
      ).getPropertyValue(parameters.argument);

      if (element.pseudoElements) {
        return $(parameters.elements).get(0).pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;
      } else {
        return windowStyle || null;
      };
    } else {
      console.error('Invalid values!');
      return false;
    };
  };

  $.fn.cssBefore = function(argument, property) {
    return setPseudoElement({
      elements: this,
      pseudoElement: 'before',
      argument: argument,
      property: property
    });
  };
  $.fn.cssAfter = function(argument, property) {
    return setPseudoElement({
      elements: this,
      pseudoElement: 'after',
      argument: argument,
      property: property
    });
  };
})();

$(function() {
  $('.element').cssBefore('content', '"New before!"');
});
.element {
  width: 480px;
  margin: 0 auto;
  border: 2px solid red;
}

.element::before {
  content: 'Old before!';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<div class="element"></div>

The values should be specified, as in the normal function of jQuery.css

In addition, you can also get the value of the pseudo-element parameter, as in the normal function of jQuery.css:

console.log( $(element).cssBefore(parameter) );

JS:

(function() {
  document.pseudoElements = {
    length: 0
  };

  var setPseudoElement = function(parameters) {
    if (typeof parameters.argument === 'object' || (parameters.argument !== undefined && parameters.property !== undefined)) {
      if (!parameters.element.pseudoElements) parameters.element.pseudoElements = {
        styleSheet: null,
        before: {
          index: null,
          properties: null
        },
        after: {
          index: null,
          properties: null
        },
        id: null
      };

      var selector = (function() {
        if (parameters.element.pseudoElements.id !== null) {
          if (Number(parameters.element.getAttribute('data-pe--id')) !== parameters.element.pseudoElements.id) parameters.element.setAttribute('data-pe--id', parameters.element.pseudoElements.id);
          return '[data-pe--id="' + parameters.element.pseudoElements.id + '"]::' + parameters.pseudoElement;
        } else {
          var id = document.pseudoElements.length;
          document.pseudoElements.length++

            parameters.element.pseudoElements.id = id;
          parameters.element.setAttribute('data-pe--id', id);

          return '[data-pe--id="' + id + '"]::' + parameters.pseudoElement;
        };
      })();

      if (!parameters.element.pseudoElements.styleSheet) {
        if (document.styleSheets[0]) {
          parameters.element.pseudoElements.styleSheet = document.styleSheets[0];
        } else {
          var styleSheet = document.createElement('style');

          document.head.appendChild(styleSheet);
          parameters.element.pseudoElements.styleSheet = styleSheet.sheet;
        };
      };

      if (parameters.element.pseudoElements[parameters.pseudoElement].properties && parameters.element.pseudoElements[parameters.pseudoElement].index) {
        parameters.element.pseudoElements.styleSheet.deleteRule(parameters.element.pseudoElements[parameters.pseudoElement].index);
      };

      if (typeof parameters.argument === 'object') {
        parameters.argument = (function() {
          var cloneObject = typeof parameters.argument.pop === 'function' ? [] : {};

          for (var property in parameters.argument) {
            cloneObject[property] = parameters.argument[property];
          };

          return cloneObject;
        })();

        if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {
          var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;

          parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;
          parameters.element.pseudoElements[parameters.pseudoElement].properties = parameters.argument;
        };

        var properties = '';

        for (var property in parameters.argument) {
          if (typeof parameters.argument[property] === 'function')
            parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property]();
          else
            parameters.element.pseudoElements[parameters.pseudoElement].properties[property] = parameters.argument[property];
        };

        for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {
          properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
        };

        parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);
      } else if (parameters.argument !== undefined && parameters.property !== undefined) {
        if (!parameters.element.pseudoElements[parameters.pseudoElement].properties && !parameters.element.pseudoElements[parameters.pseudoElement].index) {
          var newIndex = parameters.element.pseudoElements.styleSheet.rules.length || parameters.element.pseudoElements.styleSheet.cssRules.length || parameters.element.pseudoElements.styleSheet.length;

          parameters.element.pseudoElements[parameters.pseudoElement].index = newIndex;
          parameters.element.pseudoElements[parameters.pseudoElement].properties = {};
        };

        if (typeof parameters.property === 'function')
          parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property();
        else
          parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] = parameters.property;

        var properties = '';

        for (var property in parameters.element.pseudoElements[parameters.pseudoElement].properties) {
          properties += property + ': ' + parameters.element.pseudoElements[parameters.pseudoElement].properties[property] + ' !important; ';
        };

        parameters.element.pseudoElements.styleSheet.addRule(selector, properties, parameters.element.pseudoElements[parameters.pseudoElement].index);
      };
    } else if (parameters.argument !== undefined && parameters.property === undefined) {
      var windowStyle = window.getComputedStyle(
        parameters.element, '::' + parameters.pseudoElement
      ).getPropertyValue(parameters.argument);

      if (parameters.element.pseudoElements) {
        return parameters.element.pseudoElements[parameters.pseudoElement].properties[parameters.argument] || windowStyle;
      } else {
        return windowStyle || null;
      };
    } else {
      console.error('Invalid values!');
      return false;
    };
  };

  Object.defineProperty(Element.prototype, 'styleBefore', {
    enumerable: false,
    value: function(argument, property) {
      return setPseudoElement({
        element: this,
        pseudoElement: 'before',
        argument: argument,
        property: property
      });
    }
  });
  Object.defineProperty(Element.prototype, 'styleAfter', {
    enumerable: false,
    value: function(argument, property) {
      return setPseudoElement({
        element: this,
        pseudoElement: 'after',
        argument: argument,
        property: property
      });
    }
  });
})();

document.querySelector('.element').styleBefore('content', '"New before!"');
.element {
  width: 480px;
  margin: 0 auto;
  border: 2px solid red;
}

.element::before {
  content: 'Old before!';
}
<div class="element"></div>


GitHub: https://github.com/yuri-spivak/managing-the-properties-of-pseudo-elements/

Someone else commented on appending to the head element with a full style element and that's not bad if you're only doing it once but if you need to reset it more than once you'll end up with a ton of style elements. So to prevent that I created a blank style element in the head with an id and replace the innerHTML of it like this:

<style id="pseudo"></style>

Then the JavaScript would look like this:

var pseudo = document.getElementById("pseudo");

function setHeight() {
    let height = document.getElementById("container").clientHeight;
    pseudo.innerHTML = `.class:before { height: ${height}px; }`
}

setHeight()

Now in my case I needed this to set the height of a before element based on the height of another and it will change on resize so using this I can run setHeight() every time the window is resized and it will replace the <style> properly.

Hope that helps someone who was stuck trying to do the same thing.

Not the answer you're looking for? Browse other questions tagged or ask your own question.