Search code examples
javascriptparametersevent-listener

How to get a value from the InnerHTML through a event Listener if you click on or select it


I am Trying to get a value from a Event Listener , I am creating a Game cards it will do comparative among numbers , whatever I select it will take ta value and Run Function it will compare Value bellow there a sneak peak of my Game My Game

this a little of my code i just try to create first a event listener to show my number i want select

const speed = document.getElementsByClassName("speed"); //getting the class 

if I clicked on any speed from any card It will bring me the value

speed[3].addEventListener("click", powerSelect); or speed[3].addEventListener("click", battleSpeed(speed[5].innerHTML));
speed[4].addEventListener("click", powerSelect); or speed[4].addEventListener("click", battleSpeed(speed[5].innerHTML));
speed[5].addEventListener("click", powerSelect); or speed[5].addEventListener("click", battleSpeed(speed[5].innerHTML));

function powerSelect(playChoice){
    console.log("Your Choice",playChoice);
}

above i tried both events ways did not worked


Solution

  • Hi Guys i Found the solution in JavaScript Brazil community Facebook There Two ways to solve

    //using this.innerHTML or using for each

    function powerSelect() { const num = this.innerHTML;`speeds.forEach(speed =>{ speed.addEventListener(“click”, powerSelect) )} const speeds = document.getElementsByClassName("speed");

    //for (let index = 0; index < speeds.length; index++){

    // const speed = speeds[index].innerHTML

    speeds[0].addEventListener('click', powerSelect);
    speeds[1].addEventListener('click', powerSelect);
    speeds[2].addEventListener('click', powerSelect);
    console.log(num)
    

    }

    //} `