How do a script find itself.

作者:   發佈於:   #javascript

I admit it that I do not really dislike the idea of putting script tags directly inside body. That means I am not a xhtml strict person. But I can't understand that why it isn't put into the design (or implementation) to locate current script node easily.

What I'm try to solve can be described with this code snippet:

<p>
    <script type="text/javascript">
        var this_node = get_this_node(); // get the <script> node.
        var p = this_node.parentNode;    // get the <p> node.
    </script>
</p>

Turns out the only way around is to assign an element id to the script tag:

<p>
    <script id='the-script' type="text/javascript">
        var this_node = document.getElementById('the-script');
        var p = this_node.parentNode; // get the <p> node.
    </script>
</p>

This is only OK when everything is generated. Which is what I'm trying to do recently with my JavaScript::Writer perl module.