Search code examples
javascriptarraysdomevent-listenertraversal

Is there a way to identify the index of one button among a list of many buttons in the DOM when it is clicked using javascript?


I need the function to alert the index of the clicked button

var openformbtn=document.querySelectorAll('.show-form');
var formcontainer=document.querySelectorAll('.form-container');
var btnarray = Array.from(openform);
openformbtn.addEventListener('click', displayform);
function displayform(e){
    this.nextElementSibling.style.display='flex';
    var i = btnarray.index(this);
    i.style.display='flex';
}

Solution

  • When you click, it passes a click event to the function, such as:

    // We are selecting all the buttons
    const btns = document.querySelectorAll("button");
    
    // we are looping throught the selected buttons.
    btns.forEach(btn => {
      // we are adding a click event to the buttons.
      // the (e) stands for event
      btn.addEventListener("click", (e) => {
        // e stands for event
    
        // To get the clicked element you use e.target
    
    
        // document.querySelectorAll returns a NodeList
        // To use indexOf we need to make it an array.
        // That is what Array.from() is for.
        const index = Array.from(btns).indexOf(e.target);
    
        // Now we call a alert using the index
        alert(index);
      });
    });
    <button>0</button>
    <button>1</button>
    <button>2</button>
    <button>3</button>
    <button>4</button>