Home > Web Front-end > JS Tutorial > body text

How to modify pseudo-class styles with JavaScript

小云云
Release: 2017-11-29 09:42:16
Original
3294 people have browsed it

We have all heard of CSS pseudo-classes but not that JavaScript also has pseudo-classes. In projects, we often need to use JavaScript to dynamically control the styles of pseudo-elements (:before,:after), but we all know There are no pseudo-class selectors in JavaScript or jQuery. Here is a summary of several common methods.

HTML

<p class="red">Hi, this is a plain-old, sad-looking paragraph 
tag.</p>
CSS
.red::before {
content: &#39;red&#39;;
color: red;
}
Copy after login

Method 1

Use JavaScript or jQuery to switch the class name of the

element and modify the style.

.green::before {
content: &#39;green&#39;;
color: green;
}
$(&#39;p&#39;).removeClass(&#39;red&#39;).addClass(&#39;green&#39;);
Copy after login

Method 2

Dynamicly insert a new style into the existing