Change the :before selector from javascript [duplicate]

蹲街弑〆低调 提交于 2019-11-29 08:43:21

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.

user3218338

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!