获取脚本标记所在的DOM元素 [英] Get DOM element where script tag is
本文介绍了获取脚本标记所在的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写一个脚本,它将使用document.write来产生一些输出,但我需要知道它包含哪个元素,例如:
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>
我需要获得对p标签的引用...
I need to get a reference to the p tag...
谢谢!
推荐答案
在运行脚本时,文档仅部分加载。因此,您的脚本元素将是文档中的最后一个节点:
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
这篇关于获取脚本标记所在的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文