How to add text to the current position?

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

I do not want to use the document.write () method. So what should I use here for the result to be like this:

<div>HI!<span>there.</span>How are you?</div>
+4
source share
2 answers
Element

A <script>by default is executed immediately, so at the time of execution there is only <div>HI! <script />a part of the “How are you” part in the document that has not yet been processed. At this point, the processed <script>element will be the last of the script elements in your document, so you can reference it with document.scripts[ document.scripts.length - 1 ], then find its parent node and add 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/

: , , : 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>
+7

script. ( ) script..

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

All Articles