Home >Web Front-end >JS Tutorial >How to modify pseudo-class styles with JavaScript
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: 'red'; color: red; }
Method 1
Use JavaScript or jQuery to switch the class name of the e388a4556c0f65e1904146cc1a846bee element and modify the style.
.green::before { content: 'green'; color: green; } $('p').removeClass('red').addClass('green');
Method 2
Dynamicly insert a new style into the existing c9ccee2e6ea535a969eb3f532ad9fe89.
document.styleSheets[0].addRule('.red::before','color: green'); document.styleSheets[0].insertRule('.red::before { color: green }', 0);
Method 3
Create a new style sheet and insert it into the 93f0f5c25f18dab9d176bd4f6de5d30e using JavaScript or jQuery
// Create a new style tag var style = document.createElement("style"); // Append the style tag to head document.head.appendChild(style); // Grab the stylesheet object sheet = style.sheet // Use addRule or insertRule to inject styles sheet.addRule('.red::before','color: green'); sheet.insertRule('.red::before { color: green }', 0);
jQuery
$('<style>.red::before{color:green}</style>').appendTo('head');
Method 4
Use the HTML5 data-attribute and use attr() to dynamically modify it in the attribute.
<p class="red" data-attr="red">Hi, this is plain-old, sad-looking paragraph tag.</p> .red::before { content: attr(data-attr); color: red; } $('.red').attr('data-attr', 'green');
The above are the four methods we have compiled for you on how to use JavaScript to modify pseudo-class styles. We hope it will be helpful to everyone.
Related recommendations:
Example analysis of how CSS3 pseudo-classes make 3D buttons
Detailed explanation of usage examples of focus pseudo-classes in CSS
Summary of pseudo-class selectors
The above is the detailed content of How to modify pseudo-class styles with JavaScript. For more information, please follow other related articles on the PHP Chinese website!