Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append text to current position?

Tags:

javascript

<div>
HI!
<script>
var spanNode = document.createElement('span');
var textNode = document.createTextNode('there.');
//how to append here spanNode?
</script>
How are you?
</div>

I don't want to use document.write() method. So, what should I use here so the result would be like this:

<div>HI!<span>there.</span>How are you?</div>
like image 917
Navin Rauniyar Avatar asked Mar 17 '23 15:03

Navin Rauniyar


1 Answers

A <script> element by default is executed immediately, so at the moment of execution there's just <div>HI! <script /> in the document, the "How are you" part hasn't been processed yet. At this moement the currently processed <script> element will be the last of script elements in your document so you can reference it using document.scripts[ document.scripts.length - 1 ], then find its parent node and append the elements.

<div>
HI!
<script>
var spanNode = document.createElement('span');
var textNode = document.createTextNode('there.');
    spanNode.appendChild( textNode );
/* this is the currently interpreted <script> element
   so you can append a child to its parent.
*/
document.scripts[ document.scripts.length - 1 ].parentNode.appendChild( spanNode );
</script>
How are you?
</div>

http://jsfiddle.net/0LsLq9x7/

Edit: to keep the global namespace clean you could wrap the code in an anonymous function which executes immediately: http://jsfiddle.net/0LsLq9x7/1/

<div>
HI!
<script>
(function( scriptElement ){
    // these variables will be local to this closure
    var spanNode = document.createElement('span');
    var textNode = document.createTextNode('there.');
    spanNode.appendChild( textNode );
    scriptElement.parentNode.appendChild( spanNode );
// pass a reference to the script element as an argument to the function
}(document.scripts[ document.scripts.length - 1 ]));
</script>
How are you?
</div>
like image 146
pawel Avatar answered Mar 29 '23 07:03

pawel