Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DOM element where script tag is [duplicate]

Tags:

javascript

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!

like image 830
Gustav Avatar asked Aug 03 '11 20:08

Gustav


2 Answers

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
like image 190
user123444555621 Avatar answered Nov 15 '22 01:11

user123444555621


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>
like image 7
user113716 Avatar answered Nov 15 '22 00:11

user113716