Home > Enterprise >  Increment digit by one Jquery
Increment digit by one Jquery

Time:01-14

How to increment digit of the span by one every time i click on the button, if i click button 1 then span 1 should be incremented and so on ?

button 1: <a href="javascript:void(0)" ></a>
button 2: <a href="javascript:void(0)" ></a>
button 3: <a href="javascript:void(0)" ></a>
span 1: <span >1</span>
span 2: <span >1</span>
span 3: <span >1</span>

CodePudding user response:

Anchors are best for URLs and anchors (ie #pagesection). In this use case buttons are the better options.

In this answer, I give each button a data-target attribute. The value of this attribute is the ID of the element that you want to change.

I'm delegating the click handler to the body and just checking to see if what was clicked on was one of the buttons. Then I simply get the target span and its value and add 1.

document.body.addEventListener("click",(e) => {
   let el = e.target;
   if(el.classList.contains("add-menu-btn")){
     let target = document.querySelector(el.dataset.target);
     target.innerText = Number(target.innerText)   1
   }
});
<button data-target="#span1" >1</button>
<button data-target="#span2" >2</button>
<button data-target="#span3" >3</button>
<span id="span1" >1</span>
<span id="span2" >1</span>
<span id="span3" >1</span>

  • Related