Adjust the CSS within a <style> element using jQuery or javascript

What I aim to accomplish:

I intend to dynamically add and modify rules within a <style> tag using JavaScript/jQuery.

Reason behind this goal:

I am in the process of creating a color scheme editor where changes made by the user should be reflected in the CSS.

Methods attempted:

I have tried replacing the entire <style> tag with CSS generated by a JavaScript function. While it works, it seems like an excessive amount of processing for minor changes.

Another approach involves creating container <div>s that hold specific CSS classes and then finding/replacing their HTML code. See example below:

  <div id="button_background_cont">
    <style type="text/css">.buttons {background-color:#333333;}</style>
  </div>

  <div id="button_color_cont">
    <style type="text/css">.buttons {color:#ffffff;}</style>
  </div>

Both methods work but are cumbersome and not quite to my liking.

Illustration of desired outcome:

<style type="text/css" id="color_scheme">
   .buttons {background:#333333; color:#ffffff;}
</style>
<input name="button_background" id="button_background" value="#333333" />
<input name="button_color" id="button_color" value="#ffffff" />

Transform the form elements as follows

<style type="text/css" id="color_scheme">
   .buttons {background:#ff0000; color:#333333;}
</style>
<input name="button_background" id="button_background" value="#ff0000" />
<input name="button_color" id="button_color" value="#333333" />

Any suggestions?

Answer №1

To implement this functionality, you can follow this basic approach. However, there may be more efficient ways to generate the styles string. Here is an example of how it could be done:

function createStyles(){
    var btnBackground = $("#button_background").val();
    var btnTextColor = $("#button_color").val();
    var stylesTemplate = ".buttons{background:[BACKGROUND];color:[COLOR];}";

    var newStyles = stylesTemplate
                     .replace("[BACKGROUND]", btnBackground)
                     .replace("[COLOR]", btnTextColor);

    $('#color_scheme').text(newStyles);
};

$('.buttons').on('click', function(){
    createStyles();    
})

JSFIDDLE

Updated

Answer №2

If you want to change the color using jQuery, here's one way to do it:

$("#button_background").css("color",'blue')

Answer №3

Although it is possible to accomplish that task, there are simpler ways to do so (refer to this source and also this one). For instance, you can utilize the class selector in order to filter out all elements with the "old" class using $( ".oldClass" ), and then control their classes without directly editing them:

Filter and add the new class

$( ".oldClass" ).addClass(".newClass")

or remove the old class

$( ".oldClass" ).removeClass(".oldClass")

You also have the option of utilizing .css to modify a property :

$( ".oldClass" ).css("background","#ff0000")

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

Using ng-pattern to validate that a text field does not conclude with a particular term

In this code snippet, I am attempting to prevent a textfield from ending with any of the specified letters in the $scope.pointPattern variable. $scope.pointPattern = /^(?!.*ess|ence|sports|riding?$)/; $scope.error = "not valid"; Upon executio ...

How can I adjust the transparency in a JavaScript popup modal window for an ASP.Net GridView?

Recently, I added an 'onclick' event to every row of an asp gridview and the popup window that appears is functioning perfectly. Now, I'm interested in adding a transparency level to the body of the popup window for a translucent effect. Can ...

Prevent the modification of a session

My dilemma involves a piece of code that produces a random number ranging from 1 to 1000. This number is then saved as a session and sent to you via email where it needs to be entered into a form before submission. However, the issue arises when submitting ...

I encountered no response when attempting to trigger an alert using jQuery within the CodeIgniter framework

Jquery/Javascript seem to be causing issues in codeigniter. Here is what I have done so far: In my config.php file, I made the following additions: $config['javascript_location'] = 'libraries/javascript/jquery.js'; $config['javas ...

Issues encountered transferring data using wp_localize_script

I need help passing PHP data to a JavaScript script in my project. To achieve this, I am utilizing the wp_localize_script function. wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js'); wp_register_script(&apos ...

Attempting to extract content from a specific span element

I've been struggling to extract the text within a <span> element from a webpage. Every attempt I've made that doesn't result in an error has come back empty, with no output whatsoever. Here is the code I'm using: import time imp ...

Develop a line using botbuilder

Good day. I'm currently working on a vue js component that will function as a botbuilder. The main goal is to manipulate the cards displayed on the screen and establish links between them to define the flow of actions. Here's an image for referen ...

What to do when encountering a 404 Error with `meta.json` in a Next.js Application

Hello fellow developers, I'm currently facing a challenge with my Next.js application. Upon running it, the terminal keeps throwing a meta.json 404 error, and I'm stuck on how to resolve it. Here are some key points for context: The Next.js app ...

What is the most effective method for updating a className in Next.js using CSS Modules when a button is activated?

Looking to create a responsive navigation bar that transforms based on screen size? When the width reaches 600px, I'd like to hide the links and instead show a clickable nav button that reveals those options. Upon inspecting my list elements in the c ...

convert text on website using selected option from menu

A dropdown menu allows the user to choose from 3 language options: English, Spanish, and German. The intended functionality is that when a language is selected, the entire content of the site should switch to that language. Unfortunately, this feature is ...

Looking to retrieve selections when the inputValue changes in react-select?

I'm working with a react-select component and I would like to implement a feature where an API request is triggered as soon as the user starts typing in the react-select field. This request should fetch items related to the keyword entered by the user ...

Verifying internet connectivity and updating content using jQuery and JavaScript

Upon loading the page, the following functionality occurs without triggering a click event: The updated code attempts to determine if the internet connection is active. If the connection is off, the 'link' on the page will be disabled (non-click ...

Utilizing Angular Directives and Controllers for Improved Efficiency

I have developed a custom dropdown option selector which is functioning well. It includes functions to fetch data from a specified URL in order to populate a list. However, the issue arises when I attempt to reuse this component in a different section of ...

Failure to recognize AJAX content in .ready function

When using an AJAX call to load content, primarily images, I encountered a challenge. I wanted the div to fade in only after all the images were fully loaded. To achieve this, I made use of .ready method in jQuery. However, it seemed like the images were n ...

Using Jquery to Parse Json data from Twitter

I am currently facing an issue where the system is producing too many results despite working properly. Any suggestions on how to resolve this? var url = "search.twitter.com/search.json?q=%23ps3&rpp=15&from=mmgn&lang=en&callback=?"; $.getJSON(url, funct ...

Tips for incorporating a visible HTML comment in JSX code?

Currently implementing ReactJS and facing a requirement to insert visible HTML comments (visible in the html source) within JSX. Unsure of the correct approach to achieve this. A third party vendor necessitates this comment for processing purposes on the ...

Testing with Selenium to confirm the presence of a specific CSS attribute within the style attribute

I am looking to create a Selenium IDE test that will confirm the value of the bottom attribute in the "style" section below. How can I go about writing a test for this considering: The Xpath to the element is: xpath=/html/body/div/div[3]/div[2]/div/div/di ...

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

A guide to placing tooltips dynamically in highcharts column charts

I am encountering an issue with tooltips in Highcharts column charts. The problem arises when the series fill up my chart, causing the tooltip to be hidden below the series and cut off by the end of the div. You can see an example here: https://i.stack.i ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...