The following code show three buttons, I want click the one show its value. I try bt[i].firstChild.nodeValue or bt[i].innerHTML all not work.

<script type="text/javascript">  
window.onload=function(){
    var bt = document.getElementsByTagName('button');
    for (var i=0;i<bt.length;i++){
        bt[i].onclick = function(){
            alert(bt[i].firstChild.nodeValue);      //TypeError: bt[i] is undefined
        };
    }
}
</script>

<button id="first">First</button>
<button id="second">Second</button>
<button id="third">Third</button>

1 Answers

-1
Serj On

Try to implement this code using EventListener and loops for attaching for each button 'click' event listener:

const buttons = document.getElementsByTagName("button");
for(let i = 0; i<buttons.length; i++) {
 buttons[i].addEventListener("click", getValue);
}

function getValue() {
  console.log(this.innerHTML);
}
<button id="first">First</button>
<button id="second">Second</button>
<button id="third">Third</button>

end read about JavaScript HTML DOM EventListener