Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  47] [ 7]  / answers: 1 / hits: 15291  / 13 Years ago, tue, june 28, 2011, 12:00:00

I want to add a script after a div, this is what I have:



<div id=uno>insert after this</div><br />
<p>this is a paragraph</p><br />
<div>this is a div</div>

var myscript = document.createElement('script');
myscript.setAttribute('src', 'Scripts/start.debug.js');
document.body.appendChild(myscript);


and this code will ad <script src=Scripts/start.debug.js></script> at the end of the page, and i need it after div #uno. What can I use instead of document.body.appendChild?


More From » html

 Answers
93
<script>
// This function inserts newNode after referenceNode
function insertAfter( referenceNode, newNode )
{
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
insertAfter(document.getElementById(uno), newScript);
</script>


Even if a nextSibling doesn't exist in the DOM it will still work because when the second parameter of insertBefore is null then the newNode is appended to the end of the parentNode. A great description can be found here: http://www.netlobo.com/javascript-insertafter.html.


[#91447] Monday, June 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eliezerc

Total Points: 286
Total Questions: 102
Total Answers: 102

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
;