Getting Inner Html Of A Link When Clicked
Solution 1:
One solution is to send this
parameter in your function like this:
html
<ahref="#"onclick="myfun(this)">Computer Science</a><pid="putpara"></p>
js
window.myfun = function(obj) {
document.getElementById("putpara").innerHTML = obj.innerHTML;
}
this
refers to the DOM element.
Solution 2:
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
:
functionmyfun() {
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:
<ahref="#"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:
functionmyfun(element) {
document.getElementById("putpara").innerHTML = element.innerHTML;
}
Solution 3:
try this :
<a href="#" onclick="myfun(this)">ComputerScience</a>
<pid="putpara"></p>functionmyfun(obj) {
document.getElementById("putpara").innerHTML = obj.innerHTML;
}
Solution 4:
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.
Post a Comment for "Getting Inner Html Of A Link When Clicked"