cha
cha

Reputation: 13

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>

Upvotes: 0

Views: 826

Answers (1)

async await
async await

Reputation: 2395

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>

Upvotes: 1

Related Questions