7

I need to write a script that will use document.write to produce some output, but I need to know what element it is contained, example:

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

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

thanks!

Gustav
  • 413
  • 1
  • 5
  • 9

3 Answers3

11

At the time the script is run, the document is only partially loaded. So your script element would 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
user123444555621
  • 148,182
  • 27
  • 114
  • 126
  • 5
    This is not always true, however, e.g. inserting a new ` – Phrogz Nov 03 '11 at 04:36
  • @Phrogz though if you're inserting a new script tag you presumably have the ability to gather the information required before putting it in. The other case it may not be true in is when writing additional tags with `document.write` before performing the check, so be sure to do the check within your script before you write anything out. – Daniel X Moore Sep 01 '13 at 23:13
7

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>
user113716
  • 318,772
  • 63
  • 451
  • 440
-1

Why not just put an id on the relevant p tag?

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

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

jfriend00
  • 683,504
  • 96
  • 985
  • 979