I have an HTML Link and a p tag as follows:
<a href="#" onclick="myfun()">Computer Science</a>
<p id="putpara"></p>
This Is My Function :
function myfun() {
document.getElementById("putpara").innerHTML = this.innerHTML;
}
However when i click the link the content inside the paragraph tag
changes to undefined.
Seems like a silly mistake i am making.....Newbie to javascript....
this
inmyfun
in your sample, refers to the global object, which in this case would be theWindow
-object.You can fix it like this, provided you give your
a
-tag the IDlink
:If you want to learn more on why you experienced this problem, you should read up on Closures in JavaScript.
EDIT
As pointed out in a comment to my answer, a more reusable solution would be to change the HTML to this:
In this case, the
onclick
-event will be called with the corresponding DOM-element as a parameter.Then change the JavaScript-function, so that it accepts the passed in element:
One solution is to send
this
parameter in your function like this:html
js
this
refers to the DOM element.fiddle
Do it like this maybe:
Or like this(if it's not inside onload or ready function):
Explanation:
event.target
pretty much returns the object on which the event was dispatched on. According to MDN:And:
Fiddle.
try this :