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.

4
  • 3
    Probably worth looking at: stackoverflow.com/questions/280389/… But the simplest solution is to just have myFunction(this), which would explicitly pass in the the DOM <script> object Commented Apr 10, 2014 at 20:28
  • 3
    @MarcB uhh ... this would be the global context (window), not the <script> DOM node. Commented Apr 10, 2014 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. Commented Apr 10, 2014 at 20:33
  • @durbnpoisn, it's too hardcode for me ) Commented Apr 10, 2014 at 20:37

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow! Clever trick! ) Is it consistent with all rendering engines out there? Is it forward-compatible?
Your idea looks reasonable. However this trick is not working for me. It gets wrong script element.
Probably it gets complicated when you have other script elements generated on the fly by third-party services like Google Analytics etc.
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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.