Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get the dom element a function was called from

Tags:

javascript

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 i somehow get the a-tag that this function was called from?

i know i could just pass it as a parameter, but this function is used many many times on a page and i want to avoid putting the parameter everywhere.

thanks!

like image 288
clamp Avatar asked Apr 10 '12 14:04

clamp


2 Answers

Since you are using an onclick attribute (BAD!) you have to pass that into the function.

onclick="callme(this); return false;"

and the js:

function callme(el) {
  var $me = $(el);
  $me.doSomething();
}

Another option is to set the context of the function using .call().

onclick="callme.call(this,event)"

and the js

function callme(event) {
    event.preventDefault();
    $(this).doSomething();
}
like image 150
Kevin B Avatar answered Sep 25 '22 03:09

Kevin B


I have a simple JS function for that

 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 bring back the whole dom object which you can manipulate as you please, or has been said already by other users you can just use

 function callme(event) {
      $(this).toggle();
 }
like image 36
kamui Avatar answered Sep 25 '22 03:09

kamui