Jinx
Jinx

Reputation: 867

JavaScript insert element at point of execution

Is it possible to insert DOM HTML element at the point of execution of <script> tag? Like with document.write() function which immediately inserts text into DOM when executed.

[UPDATE]

Yes it is! Here's what I came up with:

var injectElement = function (element) {
    //Function that generates random id
    var randomID = function () {
        var id = '';
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for( var i=0; i < 5; i++ )
           id += chars.charAt(Math.floor(Math.random() * chars.length));
       return id;
    };

    var id = randomID();

    //Adding placeholder element
    document.write('<div id="' + id + '"></div>');

    //Injecting new element instead of placeholder
    var placeholder = document.getElementById(id)
    placeholder.parentNode.replaceChild(element, placeholder);
};

Upvotes: 2

Views: 1295

Answers (3)

frenchone
frenchone

Reputation: 1597

Use document.currentScript and fallback to document.scripts[document.scripts.length-1] if you're targetting IE

function writeHere(element)
{
 var sc = document.currentScript || document.scripts[document.scripts.length-1] ;  
 sc.parentNode.insertBefore(element, sc);
 // or in jquery $(sc).before($(element));
}

note: I didn't test document.scripts[document.scripts.length-1] thoroughly but it should work in most cases (= if you don't create script element by hand in other scripts).
And this is a fix for IE so who cares :)

Upvotes: 0

Jinx
Jinx

Reputation: 867

Ok, so I gave this one a little bit of thought and I think I have created a fail safe way to inject element into DOM after the <script> tag with something as simple as:

<script>
    injectElement(document.createElement('canvas'));
</script>

First I use document.write to insert div with random id attribute. After that, I get that placeholder with random id and replace it with my new element that I want to inject.

Genius if I may say so my self :D

Here's the code:

var injectElement = function (element) {
    //Function that generates random id
    var randomID = function () {
        var id = '';
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        for( var i=0; i < 5; i++ )
           id += chars.charAt(Math.floor(Math.random() * chars.length));
       return id;
    };

    var id = randomID();

    //Adding placeholder element
    document.write('<div id="' + id + '"></div>');

    //Injecting new element instead of placeholder
    var placeholder = document.getElementById(id)
    placeholder.parentNode.replaceChild(element, placeholder);
};

Upvotes: 0

suff trek
suff trek

Reputation: 39777

Yes this is possible:

<script>
    var arrScripts = document.getElementsByTagName('script');
    var currScript = arrScripts[arrScripts.length - 1];

    var newNode = document.createElement('div');
    newNode.innerHTML = 'This is a DIV';

    currScript.parentNode.appendChild(newNode);

</script>

This code first locates current script block within the document and then appends DOM element after it.

Upvotes: 1

Related Questions