You are here: Reference > JavaScript > client-side > selection and ranges > methods > insertNode (Range)

insertNode method (Range)

Browser support:
9
Inserts the specified node at the start of the current Range.
This method inserts the specified node into the DOM hierarchy first. The insertion point is the start position (specified by the startContainer and startOffset properties) of the current Range. After that, it sets the start position of the Range to the start position of the newly inserted element.
Note: if the specified node is already a part of the DOM hierarchy, the insertNode method removes it first.

Syntax:

object.insertNode (nodeToInsert);
You can find the related objects in the Supported by objects section below.

Parameters:

nodeToInsert
Required. Reference to the node to insert.

Return value:

This method has no return value.

Example HTML code 1:

This example illustrates the use of the insertNode method:
<head>
    <script type="text/javascript">
        function MoveButton () {
            var wanderer = document.getElementById ("wanderer");
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selection = window.getSelection ();
                if (selection.rangeCount > 0) {
                    var range = selection.getRangeAt (0);
                    range.insertNode (wanderer);
                }
            }
            else {  // Internet Explorer before version 9
                var textRange = document.selection.createRange ();
                textRange.collapse (true);
                textRange.pasteHTML (wanderer.outerHTML);
                wanderer.parentNode.removeChild (wanderer);
            }
        }
    </script>
</head>
<body>
    <div onmouseup="MoveButton ()" style="width:400px; background-color:#e0f0d0;">
        Select some text with your mouse within this field.
        When the left button is released the wanderer button is placed 
        at the beginning of the selection.
        Left mouse clicks also move the wanderer button in Internet Explorer, Firefox, Google Chrome and Safari.
    </div>
    <button id="wanderer">wanderer</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content