Skip to content Skip to sidebar Skip to footer

How To Append Text To Current Position?

HI! How a

Solution 1:

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 closurevar 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>

Solution 2:

You can first get the current script. Then add the element before (or after) the script..

<div>
HI!
<scriptid="myscript">var spanNode = document.createElement('span');
var textNode = document.createTextNode('there.');
    spanNode.appendChild( textNode );
  
    //appending the span nodevar ele = document.currentScript;   //get current script element
    ele.parentNode.insertBefore(spanNode,ele);  //append the span before the script</script>
How are you?
</div>

Post a Comment for "How To Append Text To Current Position?"