开发者

Get DOM element where script tag is [duplicate]

This question already has answers here: How may I reference the script tag that loaded the currently-executing script? 开发者_StackOverflow社区 (14 answers) Closed 8 years ago.

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").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜