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>
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>
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>
function print()
{
alert(document.getElementById('G1').innerHTML);
}
<p id="G1" onclick='print()'>Gourc'hemonnoù!</p>