Get DOM element where script tag

I need to write a script that will use document.write to generate some output, but I need to know which element it contains, for example:

<p> paragraph 1 <script src="test.js" type="text/javascript"></script> </p> 

I need to get a link to the p tag ...

thanks!

+7
source share
3 answers

At run time, the document is only partially loaded. So your script element will be the last node in the document:

 var target = document.documentElement; // start at the root element while (target.childNodes.length && target.lastChild.nodeType == 1) { // find last HTMLElement child node target = target.lastChild; } // target is now the script element alert(target.parentNode); // this is p 
+11
source

Example: http://jsfiddle.net/NqN3S/

 <p> paragraph 1 <script id="test" type="text/javascript"> var scpt = document.getElementById( "test" ); var p = scpt.parentNode; p.removeChild( scpt ); alert( "old content: " + p.innerHTML ); p.innerHTML = "some new content"; </script> </p> 
+8
source

Why not just put the identifier in the corresponding p tag?

 <p id="desiredTag"> paragraph 1 <script src="test.js" type="text/javascript"></script> </p> 

Then you can do getElementById("desiredTag") or $("#desiredTag") .

-one
source

All Articles