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

250
Vistas
Incrementing variable id using javascript button onclick event

im trying to increment the id of an element everytime i click a button

im confused why its working when for innerHTML but not for id

my markup

<p id="demo"></p>
<button onclick="myfunction()">press me</button>

incrementing inner html

<script>
    var a = 1;

    function myfunction(){
        document.getElementById("demo").innerHTML = a;
         a++;
        
    }
</script>

incrementing element variable id

<button onclick="myfunction()">press me</button>

<script>
    var a = 1;

    function myfunction(){
        document.getElementById("demo").id = a;
         a++;
    }
</script>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Please enjoy this demo on storing an element into a variable for reuse. It looks like your issue was with trying to select the element by id after the id changed.

let cntr = 1;

const demo = document.getElementById("demo");

document.querySelector("button")
.addEventListener("click", function () {
  const val = cntr % 4;
  demo.id = "ele" + val;
  cntr++;
});
.demo {
  height: 5rem;
  aspect-ratio: 1;
  border-radius: 50%;
  background: black;
  margin: auto;
  
  display: flex;
  justify-content: center;
  align-items: center;
  
  transition: background 1s;
}

#ele1 {
  background: pink;
}

#ele2 {
  background: lightblue;
}

#ele3 {
  background: lightgreen;
}
<div id="demo" class="demo"><button>Clicky!</button></div>

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