Reputation: 1329
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....
Upvotes: 2
Views: 7172
Reputation: 16570
this
in myfun
in your sample, refers to the global object, which in this case would be the Window
-object.
You can fix it like this, provided you give your a
-tag the ID link
:
function myfun() {
document.getElementById("putpara").innerHTML = document.getElementById("link").innerHTML;
}
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:
<a href="#" onclick="myfun(this)">Computer Science</a>
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:
function myfun(element) {
document.getElementById("putpara").innerHTML = element.innerHTML;
}
Upvotes: 4
Reputation: 33218
One solution is to send this
parameter in your function like this:
html
<a href="#" onclick="myfun(this)">Computer Science</a>
<p id="putpara"></p>
js
window.myfun = function(obj) {
document.getElementById("putpara").innerHTML = obj.innerHTML;
}
this
refers to the DOM element.
Upvotes: 5
Reputation: 10179
Do it like this maybe:
function myfun() {
document.getElementById("putpara").innerHTML = event.target.innerHTML;
}
Or like this(if it's not inside onload or ready function):
window.myfun = function() {
document.getElementById("putpara").innerHTML = event.target.innerHTML;
}
Explanation:
event.target
pretty much returns the object on which the event was dispatched on. According to MDN:
This property of event objects is the object the event was dispatched on. It is different than event.currentTarget when the event handler is called in bubbling or capturing phase of the event.
And:
The event.target property can be used in order to implement event delegation.
Upvotes: 2
Reputation: 1495
try this :
<a href="#" onclick="myfun(this)">Computer Science</a>
<p id="putpara"></p>
function myfun(obj) {
document.getElementById("putpara").innerHTML = obj.innerHTML;
}
Upvotes: 2