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

276
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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