0

I know you can add style to an element in javascript. E.g.

myElement.style.color = "red";

But say I wanted to do the equivalent of

hr:after {
  content: "myRuntimeValue"
}

How can I achieve that in javascript?

andrea
  • 481
  • 2
  • 8
  • 27

2 Answers2

2

You can do this indirectly via element attribute:

CSS

p#my-id::after {
    // set content to be the value of an attribute on the element p
    content: attr(data-value);
}

JS

const element = document.getElementById('my-id');
element.setAttribute('data-value', 'myRuntimeValue');
JME
  • 483
  • 2
  • 5
1

:before and :after are not actual DOM-elements... so, you can't do anything with them from JS.

But you can create two classes, with different contents and styles, and toggle the class:

JsFiddle

document.getElementById('demo').addEventListener('click', function(){
  this.classList.remove('demo');
  this.classList.add('New-demo');
});
.demo:after {
  content: " myRuntimeValue";
  color: orange;
}
.New-demo:after {
  content: " Some New Bubu!";
  color: red;
}
<p id="demo" class="demo">Click Me!</p>

With this trick, you can not only change the content, but add actual styles.

Community
  • 1
  • 1
OPTIMUS PRIME
  • 1,297
  • 9
  • 20