get parent ID in nested script

Discussion in 'Javascript' started by Andrew Poulos, Apr 28, 2008.

  1. If I have code that looks like this:

    <div id="myID">
    <script type="text/javascript">
    var foo = function() {
    // refer to the id myID here
    };
    </script>
    </div>

    how can the function "foo" reference the parent container DIV's id
    without me having to hard code it?

    Andrew Poulos
    Andrew Poulos, Apr 28, 2008
    #1
    1. Advertising

  2. Andrew Poulos wrote:

    > <div id="myID">
    >    <script type="text/javascript">
    >      var foo = function() {
    >        // refer to the id myID here
    >      };
    >    </script>
    > </div>
    >
    > how can the function "foo" reference the parent container DIV's
    > id without me having to hard code it?


    I don't think this is possible in an OO-model like javascript. The
    code itself is not part of the DOM.

    One workaround is to perform an XMLHttpRequest to the same page,
    filter on '// refer to the id myID here' and fetch the ID of its
    parent tag. You might classify this as hard code.

    --
    Bart
    Bart Van der Donck, Apr 28, 2008
    #2
    1. Advertising

  3. Andrew Poulos

    Stevo Guest

    Andrew Poulos wrote:
    > If I have code that looks like this:
    >
    > <div id="myID">
    > <script type="text/javascript">
    > var foo = function() {
    > // refer to the id myID here
    > };
    > </script>
    > </div>
    >
    > how can the function "foo" reference the parent container DIV's id
    > without me having to hard code it?
    > Andrew Poulos


    I don't know if it would be suitable in your case, but you could
    document write a marker DIV that you could search for and get it's
    parentNode.

    <div id="myID">
    <script type="text/javascript">
    var foo = function() {
    // refer to the id myID here
    var theDiv = document.getElementById("mymarker").parentNode;
    };
    document.write("<div id='mymarker'></div>");
    </script>
    </div>
    Stevo, Apr 28, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Roy
    Replies:
    2
    Views:
    3,100
  2. mark
    Replies:
    1
    Views:
    559
  3. metal
    Replies:
    8
    Views:
    492
    Bruno Desthuilliers
    Oct 30, 2009
  4. Bill S.
    Replies:
    2
    Views:
    198
    Bill S.
    May 8, 2004
  5. Penguiniator
    Replies:
    2
    Views:
    100
Loading...

Share This Page