kodder360
kodder360

Reputation: 99

how to change css background color using JavaScript?

I am having difficulty to change background color using JavaSript. I only want to change color of background property that is inside .diagnosis-kit-inner .nav-tabs .nav-item.active:after. Can anyone help me please.Can anyone help me please? Thanks

function changeColor() {
  var changeColor = document.getElementsByClassName(".diagnosis-kit-inner .nav-tabs .nav-item.active:after");

  changeColor.style.backgroundColor = 'blue';
}
.diagnosis-kit-inner .nav-tabs .nav-item.active:after {
  background-color: white;
}
<div class="diagnosis-kit-inner ">
  <ul class="nav-tabs">
    <li class="nav-item">
    </li>
  </ul>
</div>
<a href="#" onclick="changeColor()">Change Color</a>

Upvotes: 0

Views: 97

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48733

You cannot change the style of a psudo-selector, but you can use a var() for the background color and assign a default at the document :root.

You can then overwrite this using JavaScript by calling setProperty on the style of the documentElement.

This was adapted from this answer: Changing CSS pseudo-element styles via JavaScript

function changeActiveColor() {
  document.documentElement.style.setProperty('--nav-item-active-bg', 'blue');
}
:root {
  --nav-item-active-bg: white;
}

.diagnosis-kit-inner .nav-tabs .nav-item.active:after {
  color: #CCC;
  content: 'Active';
  padding: 0.25em;
  background-color: var(--nav-item-active-bg); /* Dynamic var prop */
}
<div class="diagnosis-kit-inner">
  <ul class="nav-tabs">
    <li class="nav-item active"></li>
  </ul>
</div>
<a href="#" onclick="changeActiveColor()">Change Color</a>

Upvotes: 1

Related Questions