Changing width property of a :before css selector using JQuery [duplicate]

I have a page that has an image in it and I styled it using :before CSS selectors.
The image is dynamic so it hasn't a fixed width; So I need to set :before rule's width dynamically.
I want do it in client side using JQuery.
Assume this:

.column:before{
    width: 300px;
    float: left;
    content: "";
    height: 430px;
}

.column{
    width: 500px;
    float: right;
    padding: 5px;
    overflow: hidden;
    text-align: justify;
}

How Can I only change the width property of class with :before selector (and not one without it) using JQuery?


I don't think there's a jQuery-way to directly access the pseudoclass' rules, but you could always append a new style element to the document's head like:

$('head').append('<style>.column:before{width:800px !important;}</style>');

See a live demo here

I also remember having seen a plugin that tackles this issue once but I couldn't find it on first googling unfortunately.


Pseudo elements are part of the shadow DOM and can not be modified (but can have their values queried).

However, sometimes you can get around that by using classes, for example.

jQuery

$('#element').addClass('some-class');

CSS

.some-class:before {
    /* change your properties here */
}

This may not be suitable for your query, but it does demonstrate you can achieve this pattern sometimes.

To get a pseudo element's value, try some code like...

var pseudoElementContent = window.getComputedStyle($('#element')[0], ':before')
  .getPropertyValue('content')

Pseudo-elements are not part of the DOM, so they can't be manipulated using jQuery or Javascript.

But as pointed out in the accepted answer, you can use the JS to append a style block which ends of styling the pseudo-elements.