0

Is it possible to get HTML element from which function is called in JavaScript?

For example I have this in my HTML:

<script type="text/javascript">
    function myFunction() {
        var myContainer = getElementFromWhichFunctionIsCalled(); // Possible?
        (myContainer.id == 'my-container'); // TRUE
    }
</script>

<div id="my-container">
    <script type="text/javascript">myFunction();</script>
</div>

Thank you.

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202
  • 3
    Probably worth looking at: http://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript But the simplest solution is to just have `myFunction(this)`, which would explicitly pass in the the DOM ` – Marc B Apr 10 '14 at 20:28
  • 3
    @MarcB uhh ... `this` would be the global context (`window`), not the ` – Pointy Apr 10 '14 at 20:32
  • or since you have the DIV ID'd, you can just call myFunction('my-container'). Within the function you can make use of the name you just passed in. – durbnpoisn Apr 10 '14 at 20:33
  • @durbnpoisn, it's too hardcode for me ) – Slava Fomin II Apr 10 '14 at 20:37

2 Answers2

1

The way you call it here, when myFunction is running, the document will only have been parsed up to the script element in #my-container. Because of that, you can use

var scripts = document.getElementsByTagName('script');
var currentScript = scripts[scripts.length - 1];
var myContainer = currentScript.parentNode;

to get the element.

guest
  • 6,450
  • 30
  • 44
0

I've finally came up with this solution:

Hope it helps someone.

/**
 * Creating a temporary element to fetch it's parent element.
 */
function getElementFromWhichFunctionIsCalled() {

    // Generating unique ID for temporary element.
    var trickElementId = 'trick-element-' + Math.floor(Math.random() * 100000);

    // Adding temporary element to the DOM.
    document.write('<div id="' + trickElementId + '"></div>');

    // Getting hold of added element.
    var trickElement = document.getElementById(trickElementId);

    // Getting parent element of our trick element.
    var foundElement = trickElement.parentNode;

    // Cleaning up (removing trick element from the DOM).
    foundElement.removeChild(trickElement);

    return foundElement;
}
Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202