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 :
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;
}
hello
cool
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);
}
});
});
}