Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!