HTML:
<div id="WholeNew">
<script>func2()</script>
<img src="x" onerror=func1() />
</div>
JS:
function func1()
{
console.log(arguments.callee.caller.arguments[0].target.parentNode.outerHTML);
}
function func2()
{
console.log(document.currentScript.parentNode.outerHTML);
}
Now look at the output in console:
For func1():
<div id="WholeNew">
<script>func2()</script>
<img src="x" onerror=func1() />
</div>
For func2():
<div id="WholeNew">
<script>func2()</script>
</div>
Why there's a difference in both outputs, as the element in document.callee.caller.arguments[0].target
of func1()
document.currentScript.parentNode
of func2()
is the same <div>
? I need complete outerHTML of <div>
from func2()
.
The problem is that when asking for document.currentScript.parentNode
the document is not yet ready. Try to retrieve the outerHTML
on DOMContentLoaded
:
function func2()
{
currentScriptReference = document.currentScript;
document.addEventListener('DOMContentLoaded', function(){
console.log(currentScriptReference.parentNode.outerHTML);
}, false);
}
Working plunker: https://plnkr.co/edit/koZ1xDlpFacm7r9uY8lC?p=preview
The result of console log:
<div id="WholeNew">
<script>func2()</script>
<img src="x">
</div>