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

215
Vistas
Changing :before value on button click CSS style and Javascript

I'm having some trouble changing the color of :before on a button click event. At the moment, I've got code which changes the background to red when I call the changeColor(); function but doesn't change the :before section which is the "tick" on a chat bubble I'm coding. Any ideas what I'm doing wrong?

Please see the code below:

HTML:
<p id="chatLog"></p>

CSS:
body {
background: #368dda;
}

.p {
position: relative;
font-family: sans-serif;
font-size: 18px;
line-height: 24px;
width: 300px;
background: #fff;
border-radius: 40px;
padding: 24px;
text-align: center;
color: #000;
}

.p:before {
 content: "";
 width: 0px;
 height: 0px;
 position: absolute;
 border-left: 24px solid #fff;
 border-right: 12px solid transparent;
 border-top: 12px solid #fff;
 border-bottom: 20px solid transparent;
 left: 32px;
  bottom: -24px;
}

Javascript:
function changeColor() {
document.getElementById('chatLog').style.backgroundColor = `red`;
return false;     
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Javascript has access to the DOM, but a pseudo element is generated by the css. You'd need to instead just toggle an additional css class to overwrite the original pseudo attributes attached to the element that supplies the pseudo as such.

doStuff = () => {
  const example = document.getElementById('special-p');
  example.classList.toggle('green-before');
}
p {
  font-size: 1rem;
  color: #fff;
  position: relative;
  padding: 1rem;
  outline: gray 1px dotted;
}

p:before {
  content: '';
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  background-color: #f00;
  z-index: -1;
  transition: background-color .5s ease;
}

.green-before {
  color: #000;
}
.green-before:before {
  background-color: #0f0;
}
<p id="special-p">The lazy brown dog jumps over the fence.</p>

<button onclick="doStuff()">Do Stuff</button>

You can also look at background: inherit to allow the pseudo's to inherit attributes by the parent.

about 4 years ago · Juan Pablo Isaza 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