I am calling a function test() on an anchor tag like this:-
<a class="link" onclick="test();">Hello</a>
And I am trying to access the class of the anchor inside the function test():-
function test()
{
alert($(this).attr("class"));
}
But this alerts undefined. I know that calling onclick=test(this); instead and having the following function works:-
function test(obj)
{
alert($(obj).attr("class"));
}
But, I wanted to access the properties of the element (on which the function is called) without passing a this. Just be able to get/set properties of the element (on which the function is called). Is it possible? How to do this?
In this scenario we need to make sure that HTML element owns that function which you wanna call upon click. What u actually doing is that u are using onclick attribute which just takes string parameter and completely oblivious of everything else.
In order to make HTML element owner of the function you need to map onclick property completely with your own custom function. In JavaScript you do that like that
So our code will be something like
here is the working example http://www.jsfiddle.net/VMCmb/1/.
Also please take a look at http://www.quirksmode.org/js/this.html.