Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CSS value by javascript for whole document

I want on ajax call change the values loaded from CSS file, it means not only for one element like:

document.getElementById("something").style.backgroundColor="<?php echo "red"; ?>";

but similar script which is change the css value generally, not only for element by ID, idealy like background color for CSS CLASS divforchangecolor:

CSS:

.divforchangecolor{
display: block;
margin: 20px 0px 0px 0px;
padding: 0px;
background-color:  blue;
}

HTML:

<div class="divforchangecolor"><ul><li>something i want to style</li><ul></div>
<div class="divforchangecolor">not important</div>
<div class="divforchangecolor"><ul><li>something i want to style</li><ul></div>
<div class="divforchangecolor">not improtant</div>

Ideal solution for me:

onclick="--change CSS value divforchangecolor.backgroundColor=red--"

but i need to change CSS to reach .divforchangecolor ul li and .divforchangecolor ul li:hover

like image 564
Martin Avatar asked Mar 30 '26 23:03

Martin


2 Answers

If you can't just apply the classname to these elements. You could add a new selector to your page. The following vanilla JS would be able to do that (jsFiddle).

function applyDynamicStyle(css) {
    var styleTag = document.createElement('style');
    var dynamicStyleCss = document.createTextNode(css);
    styleTag.appendChild(dynamicStyleCss);
    var header = document.getElementsByTagName('head')[0];
    header.appendChild(styleTag);    
};

applyDynamicStyle('.divforchangecolor { color: pink; }');

Just adapt the thought behind this and make it bullet proof.

like image 165
scottheckel Avatar answered Apr 01 '26 14:04

scottheckel


var elements=document.getElementsByClassName("divforchangecolor");
for(var i=0;i<elements.length;i++){
   elements[i].style.backgroundColor="red";
}
like image 30
scrblnrd3 Avatar answered Apr 01 '26 12:04

scrblnrd3