5

How to change the :before content of #abc style from javascript ?

<script>
document.getElementById('abc').style.content='-';
</script>

<style>
#abc:before{content:"+";}
</style>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356

4 Answers4

4

No, you cannot access :before or :after from javascript, because they are not a part of the DOM. However you can still achieve your goal by using CSS classes:

<script>
    document.getElementById('abc').className = "minus";
</script>

<style>
    #abc:before {content: "+";}
    #abc.minus:before {content: "-"}
</style>

In fact this approach is more unobtrusive, because you don't mix representation with javascript. Tomorrow you might want to change text "+/-" to say nice background images, in this case you don't have to touch javascript code at all.

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

As far as I know you cannot change the before since it is a pseudo element and not part of the DOM. What you can do is maybe add another class with javascript that has a seperate before specification.

Please see if this question can help you do a work-around Changing width property of a :before css selector using JQuery

Community
  • 1
  • 1
user3218338
  • 652
  • 1
  • 8
  • 20
0

jQuery cannot set css properties on :before content, since it is not contained in an element. If you want to be able to manipulate the color of the :before content with javascript, you can create an extra css class, and add/remove this class.

WhiteLine
  • 1,919
  • 2
  • 25
  • 53
0

So update #abc to

#abc {
content: attr(data-before);
}

and ensure that the element that #abc refers to has a data attribute e.g

Then in your js, you can access the data-before attribute using the HTML data API and as you modify that, the content will change too.

Does that make sense?

Hlawuleka MAS
  • 550
  • 5
  • 11