Javascript gets the dom element called by the function from
HTML part:
<a href="#" onclick="callme();return false;">foo</a> JS Part:
function callme() { var me = ?; //someway to get the dom element of the a-tag $(me).toggle(); } in the JS part, can you somehow get the a-tag from which this function was called?
I know that I can simply pass it as a parameter, but this function is used many times on the page, and I want to avoid the localization of the parameter.
thanks!
Since you are using the onclick attribute (BAD!), You must pass this to the function.
onclick="callme(this); return false;" and js:
function callme(el) { var $me = $(el); $me.doSomething(); } Another option is to set the function context using .call ().
onclick="callme.call(this,event)" and js
function callme(event) { event.preventDefault(); $(this).doSomething(); } I have a simple JS function for this
function getEventTarget(event) { var targetElement = null; try { if (typeof event.target != "undefined") { targetElement = event.target; } else { targetElement = event.srcElement; } // just make sure this works as inteneded if (targetElement != null && targetElement.nodeType && targetElement.parentNode) { while (targetElement.nodeType == 3 && targetElement.parentNode != null) { targetElement = targetElement.parentNode; } } } catch (ex) { alert("getEventTarget failed: " + ex); } return targetElement; }; in your html
<a href="#" onclick="callme.call(this,event);return false;">foo</a> in your function
function callme(event) { var me = getEventTarget(event); //someway to get the dom element of the a-tag $('#'+ me.id).toggle(); } getEventTarget () will return an entire dom object that you can manipulate as you like, or already told other users that you can just use
function callme(event) { $(this).toggle(); } Send the this parameter to your function.
<a href="#" onclick="callme(this);return false;">foo</a> function callme(me) { $(me).toggle(); } it's better not to use onlcick in html markup
$(document).ready(function() { $("a").click(callme); }) function callme() { var me = this; $(me).toggle(); }