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!
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
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>
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")
.
精彩评论