0

I'm trying to return the text of this

into an alert. Why is this returning 'undefined'?

function print()
{
  alert(this.innerHTML);
}
<p id="G1" onclick='print()'>Gourc'hemonnoù!</p>
Irfan wani
  • 4,084
  • 2
  • 19
  • 34
Posoroko
  • 189
  • 1
  • 2
  • 11
  • Inline event handlers like `onclick` are [not recommended](https://stackoverflow.com/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](https://stackoverflow.com/a/43459991/4642212) way of registering events. Always [use `addEventListener`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Inline_event_handlers_—_dont_use_these) instead. And please try using the [debugging capabilities](https://developer.mozilla.org/en-US/docs/Mozilla/Debugging/Debugging_JavaScript) of your browser, e.g. `console.log(this)` to figure out what `this` is. – Sebastian Simon Nov 29 '20 at 12:46

2 Answers2

1

When you use this inside the function, it means "this function". What you have to do is to pass the element in <p id="G1" onclick='print(this)' this in here means current element. Then inside your function you can use the element you passes.

function print(element)
{
  alert(element.innerHTML);
}
<p id="G1" onclick='print(this)'>Gourc'hemonnoù!</p>
Andam
  • 2,087
  • 1
  • 8
  • 21
0

function print()
{
  alert(document.getElementById('G1').innerHTML);
}
<p id="G1" onclick='print()'>Gourc'hemonnoù!</p>
Irfan wani
  • 4,084
  • 2
  • 19
  • 34