-1

I'm adding a class to a div in order to momentarily change its border color. But it already has a CSS rule setting its border color.

I'm guessing that is why it doesn't change. How could I achieve that?

const player = document.getElementById('player');
player.classList.add('playing');
div {
  border: 2px solid grey;
}

.playing {
  border-color: yellow;
}
<div id="player">
</div>
Joshua Chan
  • 1,797
  • 8
  • 16
brenobarreto
  • 195
  • 1
  • 11
  • The code you posted should work, so something else is preventing the border color from changing. Please include more. – rec0nstr Dec 09 '19 at 01:10

3 Answers3

1

Do you already have the div in the HTML code? Did you query it correctly to assign to the div variable? Here seems to be the "just working" code.

const div = document.querySelector('div')
div.classList.add('playing');
div {
    border: 2px solid grey;
    width: 100px; height: 200px;
}

.playing {
    border-color: yellow;
}
<div></div>
Loi Nguyen Huynh
  • 8,492
  • 2
  • 29
  • 52
0

I guess this will solve your problem.Probably you couldn't catch your div element so you had problem during your trying.

    <style>
        div{
        border: 5px solid grey;
        }
        .playing{
        border-color: yellow;
        }
      </style>

    <div>Test</div>

    <script>
        document.getElementsByTagName("div")[0].classList.add("playing");
    </script>
0

You can do it like this:

Note: This is valid for the extreme case that there is only one div on the screen or that it is the first inside the body. Fore more flexibility you can add an id to the div element and then replace document.getElementsByTagName('div')[0]; with document.getElementById('idOfDiv'); below.

function startPlaying() {
  div = document.getElementsByTagName('div')[0];
  div.classList.add('playing');
}

function stopPlaying() {
  div = document.getElementsByTagName('div')[0];
  div.classList.remove('playing');
}
div{
    border: 2px solid grey;
    padding:20px
}

.playing{
    border-color: yellow;
}
<div></div>

<input type="button" value="Start playing" onclick="startPlaying()" />
<input type="button" value="Stop playing" onclick="stopPlaying()" />
Ivan86
  • 5,695
  • 2
  • 14
  • 30