How change content value of pseudo :before element by Javascript [duplicate]

Solution 1:

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;
}

Solution 2:

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.

Solution 3:

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

Solution 4:

I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:

document.getElementById('btn_change1').addEventListener("click", function(){
    document.getElementById('test_div').title='Status 1';
});
   
document.getElementById('btn_change2').addEventListener("click", function(){       
    document.getElementById('test_div').title='Status 2';
});
#test_div {
   margin: 4em;
   padding:2em;
   background: blue;
   color: yellow;
}

#test_div:after {
   content:attr(title);
   background: red;
   padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>

<div id='test_div' title='Initial Status'>The element to modify</div>