Is it possible for javascript to get a reference to the current DOM element it is nested in? For example:
<a href=“#” onClick=“function(selfElement);”>
Which would pass into the “function()” a reference to the <a href> element?
Is it possible for javascript to get a reference to the current DOM element it is nested in? For example:
<a href=“#” onClick=“function(selfElement);”>
Which would pass into the “function()” a reference to the <a href> element?
you would pass the this keyword
<a href="#" onClick="doSomething(this);">
function doSomething(el) {
// do something with el
}
It’s not a good idea though to have a link without a useful destination. Nor is it a good idea to have javascript mixed in with the html code.
Because of this, you should separately attach the onclick event from javascript, which has the nice side-benefit of the this keyword automatically referring to the element that fired the event.
<a id="myLink" href="somePage.html">
document.getElementById('myLink').onclick = doSomething;
function doSomething() {
var el = this; // the element that fired the event
}
Another benefit is that the information about the event is also available to you as well.
<a id="myLink" href="somePage.html">
document.getElementById('myLink').onclick = doSomething;
function doSomething(evt) {
evt = evt || window.event; // The event that was fired
var targ = evt.target || evt.srcElement; // the element that was clicked
var el = this; // the element that fired the event
}