How to Modify CSS Declaration Objects in JavaScript without Overwriting Existing Styles?

Barbara Streisand
Release: 2024-10-27 01:34:30
Original
323 people have browsed it

How to Modify CSS Declaration Objects in JavaScript without Overwriting Existing Styles?

Accessing and Modifying CSS Declaration Objects

In web development, you may encounter the need to modify CSS styles without resorting to inline styling, which can overwrite existing styles and disrupt functionality. This article will demonstrate how to access and modify CSS declaration objects using JavaScript.

Consider the following CSS code:

<code class="css">.box {
  color: green;
}

.box:hover {
  color: blue;
}</code>
Copy after login

This CSS creates a box with green text that turns blue on hover. However, if you apply inline styling for color, the hover behavior will be lost:

<code class="html"><div class="box" style="color: red;">TEXT</div></code>
Copy after login

To avoid this issue, you can access the CSS declaration object and modify it directly. JavaScript provides the cssRules property on the DOM stylesheet object that corresponds to your stylesheet. You can use this property to get an array of all CSS rules.

To modify a CSS rule, you can use the style property of the rule object. For example, to change the color of the box to red, you could use the following JavaScript:

<code class="javascript">var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;

rules[0].style.color = 'red';</code>
Copy after login

Note that IE uses rules instead of cssRules.

You can see a demonstration of this technique at http://jsfiddle.net/8Mnsf/1/.

The above is the detailed content of How to Modify CSS Declaration Objects in JavaScript without Overwriting Existing Styles?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!