<分区>
我需要编写一个脚本来使用 document.write 来产生一些输出,但我需要知道它包含什么元素,例如:
<p>
paragraph 1
<script src="test.js" type="text/javascript"></script>
</p>
我需要获得对 p 标签的引用...
谢谢!
标签 javascript
<分区>
我需要编写一个脚本来使用 document.write 来产生一些输出,但我需要知道它包含什么元素,例如:
<p>
paragraph 1
<script src="test.js" type="text/javascript"></script>
</p>
我需要获得对 p 标签的引用...
谢谢!
最佳答案
在脚本运行时,文档仅被部分加载。所以您的脚本元素将是文档中的最后一个节点:
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
关于javascript - 获取脚本标签所在的 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6932679/