Home > database >  HTML, on click event, how to get the button text
HTML, on click event, how to get the button text

Time:05-22

How to get the button text or its innerHTML and use it inside the page, by not using its "name"

<button onclick="myFunction()">my text</button>

<script>
     function myFunction() {
      alert(my.text or innerHTML);
     }
</script>

CodePudding user response:

You can use innerText for that, like this:

document.getElementById('myButton').addEventListener('click', e => {
  alert(e.target.innerText)
})
<button id="myButton">
  Test button
</button>

CodePudding user response:

The function in the onclick attribute can pass the element to the function as an argument using this. The innerText or innerHTML property of that element is then referenced directly from it as shown in the snippet.

<button onclick="myFunction(this)">my text</button>

<script>
     function myFunction(element) {
      alert(element.innerText);
     }
</script>

  •  Tags:  
  • html
  • Related