Updating the CSS styles in the head tag dynamically: A step-by-step guide

Here is the HTML code I am working with:

<!DOCTYPE html>
<html>
    <head>
        <style>
            p{font-size:14pt;color:red;}
        </style>
    </head>
    <body>
        <div>
            <p class="hello"> this is a p tag </p>
            <p> this is a p without class defined</p>
            <div> this is a div tag 
                <p> this is a p tag within the div</p>
            </div>
        </div>
        <div id = "OriginalMail" class = "orgmail">
            <p> this is a Original Mail</p>
            <p class="hello"> this is a p tag </p>
            <p> this is a p without class defined</p>
            <div> this is a div tag 
                <p> this is a p tag within the div</p>
            </div>
        </div>
    </body>
</html>

I have implemented a JavaScript function to apply styles only to the div with the class name orgmail.

var sheets = document.styleSheets;
var OriginalMail = document.getElementById("OriginalMail");
var className = OriginalMail.className;
var selectorAppender = "div." + className +  " ";
for (var i in sheets) {
    var rules = sheets[i].rules || sheets[i].cssRules;
    for (var r in rules) {
        var selectorText = rules[r].selectorText;
        if(typeof selectorText !== "undefined") {
            rules[r].selectorText = selectorAppender + selectorText;
        }
    }
}

The style is successfully applied only to the targeted div with the specified class.

However, I now need to update the data within the Style tag as well.

I attempted to modify the Style tag data using the following line of code:

rules[r].selectorText = selectorAppender + selectorText;

I am encountering an issue with this. Can someone assist me in resolving this problem?

Answer №1

It was quite challenging! =)

I decided to tweak your JavaScript code in this way:

var sheets = document.styleSheets;
var OriginalMail = document.getElementById("OriginalMail");
var className = OriginalMail.className;
var selectorAppender = "div." + className +  " ";
for (var i in sheets) {
    var rules = sheets[i].cssRules;
    for (var r in rules) {
        if(typeof rules[r] === "object") {
            var selectorText = rules[r].selectorText;
            var style = rules[r].style.cssText;
            if(typeof selectorText !== "undefined") {
                sheets[i].deleteRule(rules[r]);
                var rule = selectorAppender + selectorText + " {" + style + " }";
                sheets[i].insertRule(rule,0);            
            }
        }
    }
}

Since many properties of CSS rules are read-only, the only way to update them is by deleting and adding a new CSS rule.

I even created a JSFiddle showcasing the revised code.

Cheers, Apolo

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

I need to create a login form using Angular - what steps should I follow?

I'm currently in the process of developing a login form for my website. Utilizing angular, express, and mongoDB. Below is the login function controller I have implemented: loginUser: (req, res) => { User.findOne({ username: req.bo ...

The jQuery UI Dialog refuses to close

Dealing with a perplexing quandary involving jQuery UI Dialog. The default close button on the dialog doesn't seem to be functioning properly - however, an interesting workaround exists! Intriguingly, when clicking on the adjacent areas of the button, ...

Enable the simultaneous opening of multiple accordions

I implemented accordions based on the code in this example. My goal is to allow users to open multiple accordions simultaneously. Currently, when one accordion is open and another is clicked, the first one closes. I want them all to remain open, while sti ...

JavaScript Error: Unable to execute jQuery.toJSON - It is not a valid function

I stumbled upon a Tournament Bracket and I want to bring it over to our vBulletin software. Even though the script functions properly outside of vBulletin, importing it triggers an error message. function saveFn(data, userData) { var json = jQuery.toJS ...

"Removing the default background color in the latest version of next.js: A step-by

Check out this screenshot for reference Whenever I change the gradient color in next.js, it defaults to these lines. However, switching to a blue or green color fixes the issue. The problem arises when using my current background color code: background: ...

Issue with Webstorm not automatically updating changes made to JavaScript files

On my HTML page, I have included references to several JavaScript files such as: <script type="text/javascript" src="MyClass.js"></script> When debugging in WebStorm using a Python SimpleHTTPServer on Windows with Chrome, I am able to set bre ...

After submitting the comment, you will be redirected to a different page

I am currently working on implementing a comment section for my website. I have created the comment box and successfully set up posting comments and updating them in the database. However, I am facing an issue where upon submitting a comment, the page auto ...

Creating a dependency between two checkboxes using jQueryFeedback: Looks good!

Looking for help with jQuery code to make two checkboxes dependent. When checkbox1 is checked, checkbox2 should automatically turn on. Here's my current code: //php $cus_centre = $this->createElement('checkbox', 'checkbox1'); ...

Is there a way to ensure that two block elements do not break onto different lines and instead remain alongside each

Having a little issue with my code here. I have two span elements that need to stay on the same line. They're working fine in FF and other browsers, but IE6 is giving me some trouble. Any ideas on what might be causing this? Here's the code snip ...

The horizontal overflow in the HTML code was unsuccessful

I stumbled upon an interesting issue where I applied a div with specific styling: overflow-x: scroll However, the outcome was not as expected. Instead of overflowing, the content simply started on a new line. Here is the source code for reference: & ...

jQuery generates dynamic HTML tables with a form embedded in each row, allowing users to edit the content within each row using jQuery code without triggering the submit function

After three days of struggling to find a solution, I must admit I am not well-versed in jQuery. The issue at hand involves a PHP page where users can choose a language code from a form and submit it. Upon submission, the jQuery response should build a tabl ...

Is it possible to update the background image of my iframe video?

I'm looking to customize the play button on a video displayed through an iframe on my website. Here is the code snippet I've been working with: .ytp-cued-thumbnail-overlay-image { background: url(https://www.example.com/images/video-play-butt ...

Be sure to include precise information in your ajax request when using fetch() or XMR/any other type of ajax request, just like you would with jQuery ajax

I am currently facing a challenge with my request using jQuery ajax() getJson() { $.ajax({ url: 'http://api.rss2json.com/v1/api.json', method: 'GET', dataType: 'json', data: ...

Arrange the <li> elements in a horizontal row at the bottom of the page

Is there a way to align my list items horizontally without using CSS in HTML? Additionally, I would like the li items to appear below the image at the bottom of the page. I've experimented with different attributes and searched extensively, but noth ...

Oops! The react-social-media-embed encountered a TypeError because it tried to extend a value that is either undefined, not a

I recently attempted to incorporate the "react-social-media-embed" package into my Next.js project using TypeScript. Here's what I did: npm i react-social-media-embed Here is a snippet from my page.tsx: import { InstagramEmbed } from 'react-soc ...

Is there a way to utilize jQuery to determine the distance the user has scrolled down?

Looking for some help with changing the style of an element based on scroll position using jQuery. Specifically, I want to add a class name to a div once the user has scrolled beyond 200 pixels and then remove the class name when they scroll back up to l ...

Splitting a row into four columns that will appear consistent on mobile devices

Is it possible to create a row with 4 columns in Angular 6, but have it display as 2 rows with 2 columns each on mobile devices? <div class="row" id="info" *ngIf="this.details"> <div class="col-md-12 mb-3" id="heading"> <h3>Meeting ...

What is the method for attaching a keypress event to an HTML document?

Looking to add an interactive touch to my website by creating a "press any key" page. When a key is pressed, I want it to kick off animations that bring the page to life - like sliding elements in from different directions. Open to using jQuery or plain ...

Utilize MaterialUI's stepper component to jazz up your design with

Is there a way to customize the color of a material ui Stepper? By default, the material UI stepper's icons use the primary color for both "active" and "completed" steps. class HorizontalLinearStepper extends React.Component { state = { activeS ...

Organizing form data using Vue

One of the features of my code is the ability to create dynamic input and select elements: <div v-for="(index) in rows"> <select> <option selected="true" disabled>Select Type</option> <option>Name</opti ...