Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

275
Visualizações
Javascript: How to change class and CSS when value is zero

I have 9 boxes in my html.

There is a value, id called 'lifepoint'.

There is a mouse-click function: click once & decrease one life point. This code is completed.

function decrementlife() {
        var element = document.getElementById('lifepoint');
        var value = element.innerHTML;
    
        --value;
        console.log(value);
        document.getElementById('lifepoint').innerHTML = value;
        if(value <= 0) { alert("Game Over!")};
    }

Also, there is a css style, called 'crackbox'.

.crackbox {
    position: relative;
    background: linear-gradient(0deg, black, rgb(120, 120, 120));
    width: 12vh;
    height: 12vh;
    border-radius: 30%;
    margin: 5px;
}

I want to change all box class from 'box' to 'crackbox' if life point is zero. Therefore, all box style can be 'crackbox'.

The below code is fail...

$(document).ready(function () {
      $(".box").each(function() {
        document.getElementById('lifepoint').innerHTML = value;
        if(value <= 0) { 
          ".box".toggleClass('crackbox')
        };

      })
    });

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The simplest way would be to use querySelectorAll and loop through the elements:

for(let i = 0, list = document.querySelectorAll(".box"); i < list.length; i++)
{
  list[i].classList.toggle('crackbox');
}

Or shorter ES6 version:

[...document.querySelectorAll(".box")].forEach(el => el.classList.toggle('crackbox'))
about 4 years ago · Santiago Trujillo Relatório

0

Instead of using document ready, call another function from decrement life if the value turns 0. I am writing the code for your help.

function decrementlife() {
    var element = document.getElementById('lifepoint');
    var value = element.innerHTML;

    --value;
    console.log(value);
    document.getElementById('lifepoint').innerHTML = value;
    if(value <= 0) { changeClass(); alert("Game Over!")};
}

function changeClass(){
   $('.box').addClass('crackbox').removeClass('box');
}

Hope, it helps!!

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda