Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
CSS doesn't change background when adding class

I'm trying to build a selection menu and I want to change the background color of a button when it is clicked. I'm using this code:

#sort-select {
  background-color: lightgray;
}
    
.sort-select-active {
  background-color: grey;
}
<div id="sort-contain">
   <div id="sort-select">
     Selected
    </div>
</div>

And I try to apply the sort-select-active class to my sort-select div using this JS code:

var selected = false;
select.onclick = (e) => {
   selected = !selected;
   if (selected)
      select.classList.add("sort-select-active");
   else 
      select.classList.remove("sort-select-active");
};

The class is successfully added to the element, but the background color doesn't change. Is there a conflict between the different background colors defined?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You set a background-color via an id, then you set an other via a class, the first one will always be applied, cause has an higher priority. Change the #sort-select id by a class, or use inline styles like so :

var selected = false;

select.onclick = (e) => {
    selected = !selected;

    if (selected)
    
      slect.style.backgroundColor ="gray"
    else 
     slect.style.backgroundColor ="lightgray"
};

or add !important word like so :

.sort-select-active {
  background-color: grey!important;
}
over 4 years ago · Santiago Trujillo Denunciar

0

Check this out. I added !important in the css class

var select = document.getElementById("sort-select")
var selected = false;

select.addEventListener("click", (e) => {
  selected = !selected;
  if (selected) {
    select.classList.add("sort-select-active");
  } else {
    select.classList.remove("sort-select-active");
  }

});
#sort-select {
  background-color: lightgray;
}

.sort-select-active {
  background-color: grey !important;
}
<div id="sort-contain">
  <div id="sort-select">
    Selected
  </div>
</div>

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda