Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!