9

I want to replace #789034 code to another code like #456780 where ever it finds in main.css using jquery

I am having a main.css file something like below :

.common-color
{
  color:#789034;
}

.new-cls
{
  border-color:#789034;
  height:300px;
}

.awesome-one
{
  background-color:#789034;
  height:200px;
  width:300px;
}

I want to replace #789034 code to another code like #456780 where ever it finds in main.css using jquery like :

$(each where code=#789034)
{
  set code: #456780;
}
Gary
  • 13,303
  • 18
  • 49
  • 71
techsolver
  • 103
  • 1
  • 1
  • 7
  • Maybe you should have a single class having `color: #789034;` and add this class to all the elements where this color is required. And then it'll be easy to change color using jQuery: `$('.myClass').css('color', '#456780');` – Tushar Jun 09 '15 at 05:04
  • its not practically possible, because i am using it on server properties, like border-color:#789034- Think i made a common color class for the code how to pass that class for border color--like 1px solid-- .comon-color. – techsolver Jun 09 '15 at 05:06
  • means ?? actually i clearly said i want to replace a specific color code to other on all places in one go using jquery- Your code selecting attribute, i want only code code to new color code – techsolver Jun 09 '15 at 05:18
  • Really sorry, if i was rude - that was not my intention, really sorry,yes, i it was close and thanks a lot, just it has extra thing i.e attribute, i don't want attribute as parameter. – techsolver Jun 09 '15 at 05:27
  • Possible duplicate of http://stackoverflow.com/questions/27084411/modify-css-rules-with-javascript-or-jquery (which doesn't have an accepted answer yet either) – connexo Jun 09 '15 at 05:29

5 Answers5

11

Here is a solution which I'll explain step-by-step.

First, call colorReplace("#789034", "#456780");. The first value is the target color, and the second is the replacement color.

Inside it, $('*').map(function(i, el) { will select all tags in the DOM tree. For each element, its getComputedStyle(el) styles array is returned. You can customize the selector for faster processing (e.g. $('div').map(function(i, el)) {).

All style attributes containing "color" (e.g. background-color, -moz-outline-color, etc.), it will be checked if the color value is equal to your target color. If so, it will be replaced with the target color.

Colors are returned like rgba(0,0,0,0) or rgb(0,0,0), not like #FFFFFF, so a quick conversion is done from rgb to hex for the comparison. That uses the internal rgb2hex() function.

I hope this is what you are looking for.


function colorReplace(findHexColor, replaceWith) {
  // Convert rgb color strings to hex
  // REF: https://stackoverflow.com/a/3627747/1938889
  function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    function hex(x) {
      return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
  }

  // Select and run a map function on every tag
  $('*').map(function(i, el) {
    // Get the computed styles of each tag
    var styles = window.getComputedStyle(el);

    // Go through each computed style and search for "color"
    Object.keys(styles).reduce(function(acc, k) {
      var name = styles[k];
      var value = styles.getPropertyValue(name);
      if (value !== null && name.indexOf("color") >= 0) {
        // Convert the rgb color to hex and compare with the target color
        if (value.indexOf("rgb(") >= 0 && rgb2hex(value) === findHexColor) {
          // Replace the color on this found color attribute
          $(el).css(name, replaceWith);
        }
      }
    });
  });
}

// Call like this for each color attribute you want to replace
colorReplace("#789034", "#456780");
.common-color {
  color: #789034;
}
.new-cls {
  border-color: #789034;
  border-width: 4px;
  border-style: solid;
}
.awesome-one {
  background-color: #789034;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="common-color">color</div>
<div class="new-cls">border-color</div>
<div class="awesome-one">background-color</div>
Drakes
  • 23,254
  • 3
  • 51
  • 94
  • Where is it getting CSS rules from? `getComputedStyle`? – Anthony Jun 09 '15 at 06:50
  • Yes, `getComputedStyle` will return an impressive array of computed styles. This solution filters on those styles which contain "color", then a comparison is performed, and a color replacement if needed – Drakes Jun 09 '15 at 06:58
  • @Drakes How to replace with if css is look like color: #efefef !important; – Prasant Kumar Oct 26 '18 at 18:07
  • You might be interested to know that (after 4 years) this answer is being [discussed on meta](https://meta.stackoverflow.com/questions/380430/is-there-any-recourse-after-a-dispute-that-has-already-been-decided) – Icepickle Feb 23 '19 at 00:22
  • @Icepickle Thanks for the heads up – Drakes Feb 23 '19 at 17:17
  • Sure, I think one should have the possibility to defend himself – Icepickle Feb 23 '19 at 19:20
2

Why, its elementary, dear Watson. Just grab all possible style-keys, check if they contain the word color, then replace all occurrences of the color with the new one using a complex regex system.

// gathers all style "keys" like height, width, color, etc
var keys = Object.values(window.getComputedStyle($('html').get(0)));
// removes any style keys which are not color related
var filteredKeys = keys.filter(function (key){return key.indexOf('color') > -1});
// parses the hex string of the color to be replaced into its R, G, and B parts and stores them in an array
var colors = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec("#789034").splice(1,3); 
// converts these hex strings to decimal and combines them into a "rgb(#, #, #)" formatted color string
var rgb = 'rgb(' + colors.map(function (color){return parseInt(color, 16)}).join(', ') + ')';
// go through each element in the page
$("*").each(function (index, element) {
    // go through each color-related style "key"
    filteredKeys.forEach(function(key) {
        // if the element's value for this key matches the color to be replaced...
        if ($(element).css(key) == rgb) {
            // ...replace that color with the replacement color
            $(element).css(key, "#456780");
        }
    });
});
div {
    height: 50px;
    width: 50px;
}
.common-color {
    color:#789034;
}
.new-cls {
    border-style: solid;
    border-color:#789034;
}
.awesome-one {
    background-color:#789034;
    height:200px;
    width:300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="common-color">hello</div>
<p class="new-cls">cool</p>
<div class="awesome-one"></div>

EDIT:

Or, if you would rather, here is a simple function to use. Color 1 will be replaced by color 2:

function replaceColor(color1, color2) {
    var keys = Object.values(window.getComputedStyle($('html').get(0)));
    var filteredKeys = keys.filter(function (key){return key.indexOf('color') > -1});
    var colors = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(color1).splice(1,3); 
    var rgb = 'rgb(' + colors.map(function (color){return parseInt(color, 16)}).join(', ') + ')';
    $("*").each(function (index, element) {
        filteredKeys.forEach(function(key) {
            if ($(element).css(key) == rgb) {
                $(element).css(key, color2);
            }
        });
    });
}
omikes
  • 8,064
  • 8
  • 37
  • 50
2

You can achieve this functionality by using CSS variables. Define a variable in your main.css file.

:root {   
    --color1: #789034; 
}

and use this variable instead of color code.

.common-color
{
  color: var(--color1);
}

Now you can change the color by implementing the following function through passing new color in the parameter.

function ChangeColor1(newColor)
{
  document.documentElement.style.setProperty('--color1',newColor);
}
Sami Ullah
  • 121
  • 6
1

You might want to try the following:

Put your stylesheet inline into the document, wrapped by a style tag:

<style id="myStyles" type="text/css"> /* all your css here */ </style>

Now you can probably get all the contents of this via

let myCss = document.getElementById('myStyles').innerHTML;

Then go ahead and do the replacement magic:

myCSS = myCSS.replace(/#789034/g, "#456780");

And in a last, hopeful effort, put it back in the DOM:

document.getElementById('myStyles').innerHTML = myCss;

But even if this should work, it seems to me very probable that you are bringing an XY problem.

connexo
  • 53,704
  • 14
  • 91
  • 128
-2

you might consider changing it with jquery.

$(function() {
  $('.awesome-one').hover( function(){
     $(this).css('background-color', '#789034');
  },
  function(){
     $(this).css('background-color', '#456780');
  });
});
Alex
  • 47
  • 5
  • your code is just for background, i clearly mentioned that it should change at all place where it found #789034 to this #456780- Thanks – techsolver Jun 09 '15 at 04:53