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

144
Vistas
How to get an HTML element to always display 0 as a number when using Javascript

I've started coding roughly a month ago, so thanks for your understanding if this could've been explained better.

I am trying to have a span always display 0 when clicking a button that decreases the original amount. Instead of that happening, I am continuously getting negative numbers.

<span class="badge" id="num">40</span> to be <span class="badge" id="num">0</span> after clicking the button with this function

function connectionRequestCount(num) {
  document.querySelector(num).innerText--
}

instead, it continues with negative numbers when clicking the button <span class="badge" id="num">-5</span> and so on.

I've also tried getElementById & ClassName.

Any guidance would be much appreciated.

Thanks

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If you want to prevent the number from decreasing when it is zero, just check within the function:

function connectionRequestCount(num) {
  +document.querySelector(num).innerText && document.querySelector(num).innerText--
}

This makes sure that num's text isn't 0 before decrementing it.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could do something like this:

function connectionRequestCount(num) {
  if(document.querySelector(num).innerText!=0){
    document.querySelector(num).innerText--;
  }
}
<span class="badge" id="num">40</span>
<button onclick="connectionRequestCount('#num')">Click Me!</button>

So when ever the button is clicked at 0, because of the if statement it will not go inside and not decrement the value then.

Hope that helps you
Thank You!

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