Use JavaScript to alter a CSS rule within an object

Similar Question:
Changing a CSS rule-set from Javascript

I am curious to know if it is possible to adjust Css stylesheet declarations without using inline styling.

For instance, consider the following example :

<style>
    .box {color:green;}
    .box:hover {color:blue;}
</style>

<div class="box">TEXT</div>

This code results in a box with blue text that changes to green on hover.

If I apply inline styling for the color attribute, the hover effect will be lost :

<div class="box" style="color:red;">TEXT</div>

Here, the text in the box will always appear red.

Therefore, my question is how one can access and modify the css declaration object instead of replacing styles with inline ones.

Thank you.

Answer №1

To update your style rule, access the cssRules property on the DOM stylesheet object that corresponds to your initial stylesheet.

var sheet = document.styleSheets[0];
var rules = sheet.cssRules || sheet.rules;

rules[0].style.backgroundColor = 'blue';

Keep in mind that Internet Explorer uses rules instead of cssRules.

You can see an example here: http://jsfiddle.net/8Mnsf/1/

Answer №2

To effectively manage your styles, define classes for different elements and use JavaScript to add or remove these classes as needed.

Applying styles directly to an element will take precedence over any other CSS rules that may be in place.

UPDATE: If you prefer a different approach, consider using the cssText property. Check out this example cssText property example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The MUI Modal is too large for the display

I'm using a Modal component from MUI in my project and I am facing an issue with displaying a large JSON object inside the modal. The problem is, the top of the modal extends beyond the screen height and even after making it scrollable, I am unable t ...

Is there a more concise method for accepting a collection of interfaces in TypeScript?

Issue I am facing a simplified version of a problem with my model: Here is how my model currently looks: interface Instrument { name: string; // ...more properties shared by all instruments... } interface Guitar extends Instrument { type: &q ...

Tips for applying textures dynamically to MeshPhongMaterial?

When trying to apply a texture on a THREE.MeshPhongMaterial, the texture fails to load. Here's the code snippet: let earth_geometry = new THREE.SphereGeometry(450, 10, 10) let earth_material = new THREE.MeshPhongMaterial({ emissive: 0xffffff }) ...

Performance of Bloom Effect in Three.js

The frame rate ranges from 50 to 60fps without the bloom effect being applied. renderer.render( scene, camera ); However, once the bloom effect is added, the frame rate drops significantly to just 10fps. camera.layers.set( BLOOM_SCENE ); bloomComposer.r ...

Regex tips: Matching multiple words in regex

I am struggling with creating a simple regex. My challenge is to write a regex that ensures a string contains all 3 specific words, instead of just any one of them: /advancebrain|com_ixxocart|p\=completed/ I need the regex to match only if all thre ...

Obtaining every PDF file linked within a designated div/table section of a website

Is there a way to download all PDFs linked in a table on a webpage using javascript? Edit: To clarify, I am trying to find a solution where Javascript can automatically download all the PDFs contained within a specific table on a webpage viewed in a brow ...

A pair of div elements within one section

Can you explain why the following HTML code uses two divs, one with a class and the other with an ID, instead of just using one of them to assign properties? .header { background-image: url("https://s3.amazonaws.com/codecademy-content/courses/web-101/ ...

Utilizing a fallback option for HTML5 video with a flash player and the ability to manipulate the

My dilemma involves an HTML5 video where I am utilizing jquery to interact with the player using the code snippet: video.currentTime += 1;. However, when Internet Explorer switches to Flash plugins, my JQ commands cease to function. How can I manage and co ...

Encountering an AWS Cognito issue while using Angular 4: Error message indicates configuration is missing a

I'm currently in the process of developing a web application that heavily relies on AWS services for its backend infrastructure. As of now, I am utilizing AWS Cognito to manage user sessions within the application. In my development work, I am using A ...

What is the method for viewing the content within div tags on an apex page?

Locationbox is a system outside of Salesforce, similar to Google Maps. An example can be viewed here; I am aiming to integrate it into the Salesforce platform. The first script tag fetches JavaScript code from the Locationbox service. Once the startup() f ...

Tips to prevent responseText from displaying Oracle errors when an insertion into the database fails

On my website, data is transferred from JavaScript to PHP. If the process goes smoothly, PHP should return a message like "user created successfully." However, in case of errors, it should only display "user could not be created" or "username already exist ...

I'm struggling to get this if statement to function properly in my JavaScript code - can anyone help? :)

I have encountered an issue with two functions that are meant to retrieve the user_id of a user. One function obtains the session user_id, while the other retrieves the id from the URL like this: profile.html?id=123. Below is the code snippet: // Extracti ...

Problems with passing state parameters in AngularJS UI-Router

I recently set up my configuration file in a simple way $stateProvider .state('app', { 'url': '/app', 'abstract': true, 'templateUrl': 'views/layout/index.htm ...

Dynamic positioning causes the fixed navigation bar to overlay content

I am currently working on designing a single-page website that consists of multiple sections. However, I am encountering an issue where clicking on a navigation bar link causes the page to scroll to the desired section but covers some content in the proces ...

Looking for a way to transfer the value of a variable to a PHP variable using any script or code in PHP prior to submitting a form?

Within this form, the script dynamically updates the module dropdown list based on the selected project from the dropdown box. The value of the module list is captured in a text field with id='mm', and an alert box displays the value after each s ...

The PHP script encountered an issue when trying to pass a MySQL request through to the getJSON() function

Seeking guidance from an expert on the following enigma. In my HTML, I utilized getJSON(). When using a hardcoded array that can be json_encoded (by setting $DEBUG = true), the data is passed to JavaScript for browser display successfully. However, encou ...

While implementing a delete feature in a CRUD Angular application, why am I encountering a compilation error stating that the property _id does not exist in the array?

Encountering an error while working on a MEAN app with Angular, as the compiler does not seem to accept direct manipulation of the array using the this keyword. Here is an example where the code triggers a compilation error: deleteTodo(todo) { this.t ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

Fetching data from Page 1 and passing it to Page 2 using Javascript

I'm currently experiencing an issue with my AJAX function where it needs to transfer a value from page 1 to page 2 for storage. Let's start with the AJAX function on page one: top.location.href = 'http://www.something.com/redirect.php?emai ...

Automatically capitalizing user input in React

I have implemented an input field that accepts user input and made it appear as if the first letter is automatically capitalized using CSS with textTransform: capitalize. However, when I assign a useState variable to the input field, the value does not ret ...