get parent ID in nested script

A

Andrew Poulos

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
 
B

Bart Van der Donck

Andrew said:
<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.
 
S

Stevo

Andrew said:
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>
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top