JavaScript insert element at point of execution

javascript set element position
javascript position
javascript innerhtml append
javascript insert html after element
javascript get element position from top of page
js add style to class
create element javascript
insertadjacenthtml

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);
};

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.

dom - JavaScript insert element at point of execution, Yes this is possible: <script> var arrScripts = document.getElementsByTagName('​script'); var currScript = arrScripts[arrScripts.length - 1]; var newNode  The element inside an element is nothing but for instance a span element inside a div element. Javascript has provided .contains() method to find out whether an element contains another element. This method actually returns true if the condition is satisfied else returns false .

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);
};

Modifying the document, node.append(nodes or strings) – append nodes or strings at the The insertion points are actually the same, but this method inserts HTML. A code inside functions or objects is run whenever that function or object is called. If it is called from code that is directly in the head or body of the page, then its place in the execution order is effectively the point at which the function or object is called from the direct code.

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 :)

Safely inserting external content into a page, This could be something as simple as including JavaScript code to safely add them to a page: the standard DOM node creation methods or jQuery. library strips anything that could lead to script execution from HTML,  Click the Elements tab. Go the element that you want to set the breakpoint on. Right-click the element. Hover over Break on then select Subtree modifications, Attribute modifications, or Node removal. Figure 5: The context menu for creating a DOM change breakpoint Types of DOM change breakpoints. Subtree modifications. Triggered when a child of

Element.innerHTML, The Element property innerHTML gets or sets the HTML or XML markup To insert the HTML into the document rather than replace the However, there are ways to execute JavaScript without using <script> elements,  JavascriptWeb Development Front End Technology. To delay a function call, use setTimeout () function. setTimeout (functionname, milliseconds, arg1, arg2, arg3) The following are the parameters −. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds.

1. Loading and Execution, Loading and Execution JavaScript performance in the browser is arguably the most the JavaScript will insert content into the <p> , introduce additional elements, The JavaScript file will begin downloading at the point that the <​script> tag is  Creating new HTML Elements - insertBefore() The appendChild() method in the previous example, appended the new element as the last child of the parent. If you don't want that you can use the insertBefore() method:

JavaScript DOM Nodes, To add a new element to the HTML DOM, you must create the element (element node) first, and then Then execute the remove() method on that element:. Many programming languages have a sleep function that will delay a program’s execution for a given number of seconds. This functionality is absent from JavaScript, however, owing to its

Comments
  • Why what are you trying to achieve? Why not simple place a placeholder there (e.g. an empty DIV) and append elements there?
  • So you want to do the same as document.write does, but without document.write?
  • @bfavaretto if I pass object to document.write it'll convert it to a string. I want to insert html element at the place of <script>
  • @YuriyGalanter i want to insert canvas element without having to reference id. You just place script in body of a document like this <script>game.createCanvas();</script>
  • That really isn't how that's done. You need to put a place-holder element in the body, something you can find by ID, and then append a <canvas> element to it with some script either running in the <head> or in an external .js file.
  • This is not failproof
  • A safer option is using <script id="something">, then getting the script element by id.
  • @bfavaretto completely agree and this is what I was doing initially. But then OP stated he wanted to do this "without having to reference id."
  • @bfavaretto yes, this was supposed to be my fallback. But this was interesting to know.
  • There're other way to identify current script block (like placing a unique string within the block). Whatever works best.