Razel Marquez Bigayan
Razel Marquez Bigayan

Reputation: 45

HTML, on click event, how to get the button text

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>

Upvotes: 1

Views: 4861

Answers (2)

xijdk
xijdk

Reputation: 500

You can use innerText for that, like this:

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

Upvotes: 5

Dave Pritlove
Dave Pritlove

Reputation: 2687

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>

Upvotes: 1

Related Questions