0

i just want try make a webpage where there is 4 button with different value , any time the user click a button it should prompt an title showing a message depending on the button .

i have an HTML document where a have 4 button inside a div like that

    <div id="lala">
        <button type="button" >1</button>
        <button type="button" >2</button>
        <button type="button" >3</button>
        <button type="button" >4</button>
    </div>

in Js folder i have :

function myFunction( nbr ){

return `button ${nbr} is clicked` // for demonstration purpose only

}

const h2 = document.createElement('h2') ;

const btnns = document.querySelectorAll('button')

btnns[0].addEventListener('click' , function(){h2.innerText = myFunction(btnns[0].innerHTML)}) btnns[1].addEventListener('click' , function(){h2.innerText = myFunction(btnns[1].innerHTML)}) btnns[2].addEventListener('click' , function(){h2.innerText = myFunction(btnns[2].innerHTML)}) btnns[3].addEventListener('click' , function(){h2.innerText = myFunction(btnns[3].innerHTML)})

document.body.appendChild(h2)

All things work well , but i want know if their is another solution to avoid re-taping the same code for every btn of the array returned from document.querySelectorAll('button')

i tried : - the for..of loop ...........not work - for (var i = 0 ; i < arr.lenth ; i ++ ) ........not work - added a parametre in the function of addEvent listner like this : element.addeventlistener('click', function(btn){...myfunction(btn.innerHTML) })
....also not work

0 Answers0