tags:

views:

42

answers:

3

I got some javascript inside document.body that is calling a function. Now i'm askin myself, if it is possible(within the function), to get that calling domnode, without passing it to the function?

+2  A: 

The 'this' keyword may be what you need. Info here: http://www.quirksmode.org/js/this.html

Scott Saunders
A: 

There are two ways to do this. One is to use 'this' inside the function. It references the execution scope, which in your case would be the dom element.

However, as soon as you start working with objects that approach could become problematic so it would be better to pass the event and use its target. Somewhat like so:

... onclick="myObject.myFunction( event )" ..

myClass.prototype.myFunction = function ( event )
{
   event.target == myNode
}

Of course with the latter approach you actually get access to a whole slew of other things you might want to do with the event :)

Swizec Teller
A: 

I'm not sure what you mean by "some javascript inside document.body".

If it's an event handler, you can get to event target element like this:

function myHandler(e){
    e = e || window.event; /* IE fallback */
    var node = e.target || e.srcElement; /* IE fallback */
}

But if it's a piece of code inside a <script/> element (inline code or from external file) it is also possible to find out where in the DOM tree it is executed:

 <div>
 <script type="text/javascript">
 (function(){
   var scripts = document.getElementsByTagName('script');
   var node = scripts[ scripts.length-1 ].parentNode;
 }())
 </script>
 </div>

The second example uses an anonymous function which executes immediately, that means the <script/> element is the last one in DOM tree at the moment of execution. So you can access its parent node to find out where in the DOM tree your function is.

pawel