How to change the :before content of #abc style from javascript ?
<script>
document.getElementById('abc').style.content='-';
</script>
<style>
#abc:before{content:"+";}
</style>
How to change the :before content of #abc style from javascript ?
<script>
document.getElementById('abc').style.content='-';
</script>
<style>
#abc:before{content:"+";}
</style>
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.
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
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.
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?