In the case you are asking about, this represents the HTML DOM element.
So it would be the <a> element that was clicked on.
In the case you are asking about, this represents the HTML DOM element.
So it would be the <a> element that was clicked on.
It refers to the element in the DOM to which the onclick attribute belongs:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
function func(e) {
$(e).text('there');
}
</script>
<a onclick="func(this)">here</a>
(This example uses jQuery.)
Videos
The code that you have would work, but is executed from the global context, which means that this refers to the global object.
<script type="text/javascript">
var foo = function(param) {
param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>
You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this.
<script type="text/javascript">
document.getElementById('bar').onclick = function() {
this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>
You can always call funciton differently: foo.call(this); in this way you will be able to use this context inside the function.
Example:
<button onclick="foo.call(this)" id="bar">Button</button>
var foo = function()
{
this.innerHTML = "Not a button";
};
That's because you aren't passing a reference to this in the JavaScript function call. this in the JavaScript function doesn't refer to the same object as in the onClick example. Try this instead:
<li onClick="foo(this)"></li>
function foo(item){ alert(item.tagName); }
In an inline listener:
> <li onClick="alert(this.tagName)"></li>
The onclick attribute value is effectively wrapped in a function and called with the element set to this, e.g.
function anon() {
/* attribute value */
}
anon.call(element);
When you put a function in the body, you are essentially getting:
function anon() {
foo();
}
Here, this within anon will be the element, but since foo is called without setting this, it will be undefined. In non-strict mode, this will default to the global object (window in a browser). In strict mode, this inside foo will be undefined.
One solution is to pass an element reference to the function:
<li onclick="foo(this)" ... >
then in the function:
function foo(callingElement) {
...
}
or even:
<li onclick="foo.call(this)" ... >
function foo() {
var callingElement = this;
}