How change content value of pseudo :before element by Javascript

Update (2018): as has been noted in the comments, you now can do this.

You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.


You can use CSS variable

:root {
  --h: 100px;
}

.elem:after {
  top: var(--h);
}

let y = 10;

document.documentElement.style.setProperty('--h', y + 'px')

https://codepen.io/Gorbulin/pen/odVQVL


I hope the below snippet might help, you can specify the content value you want via JS using the CSS attr() function. Below you have two options: to use JavaScript or jQuery:

jQuery:

$('.graph').on('click', function () {
    //do something with the callback
    $(this).attr('data-before','anything'); //anything is the 'content' value
});

JavaScript:

var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
    event.target.setAttribute('data-before', 'anything');
});

CSS:

.graph:before {
    content: attr(data-before); /* value that that refers to CSS 'content' */
    position:absolute;
    top: 0;
    left: 0;
}