Cristian Muscalu
Cristian Muscalu

Reputation: 9935

change css from javascript

I need to change this

body.sidebar_b .sidemenu {
background-color: rgba(0, 0, 0, 0.7) !important;
}

into this:

body.sidebar_b .sidemenu {
background-color: rgba(255, 255, 255, 0.7) !important;
}

, but don't have access to edit neither html or css files!

The only thing i can do is add a small javascript code inside the footer section.

This is few examples of what i tried so far, but seems i'm going in wrong direction.

1#
<script>
$(document).ready(function() {
    $('body.sidebar_b .sidemenu').css({
'background-color' : 'rgba(255, 255, 255, 0.7)'
});
});
</script>

2#
<script>
$(document).ready(function(){
  var cols = document.getElementsByClassName('sidemenu');
  for(i=0; i<cols.length; i++) {
  cols[i].style.backgroundColor = 'white';
 }
 });
</script>

Upvotes: 0

Views: 72

Answers (2)

Quentin
Quentin

Reputation: 944441

The problem is that the CSS rule is !important and the rule you are adding is not.

jQuery doesn't provide an API for setting important rules so you need to go down to the DOM for that.

$(document).ready(function() {
  $('body .sidebar_b .sidemenu').each(function() {
    console.log(this);
    this.style.setProperty("background-color", "rgba(255, 255, 255, 0.7)", "important");
  });
});
body .sidebar_b .sidemenu {
  background-color: rgba(0, 0, 0, 0.7) !important;
  color: white;
}
body {
  background: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar_b">
  <div class="sidemenu">
    Note that the class has been moved off the body for the same of this demo
  </div>
</div>

Upvotes: -1

sadpanda
sadpanda

Reputation: 213

Maybe something like this?

function addNewStyle(newStyle) {
    var styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(styleElement);
    styleElement.appendChild(document.createTextNode(newStyle));
}

addNewStyle('body.sidebar_b .sidemenu { background-color: rgba(255, 255, 255, 0.7) !important;}’);

Upvotes: 2

Related Questions