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

deleteFromDocument method (selectionRange)

Browser support:
9
Removes the contents of the current selection from the document.
Note: The selectionRange object and its deleteFromDocument method are supported in Internet Explorer from version 9.
The deleteFromDocument method is supported but does not work in Opera, use the getRangeAt and deleteContents methods instead in that browser.
The clear method provides similar functionality in Internet Explorer (in all versions). See Example 2 for details.

Syntax:

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

Return value:

This method has no return value.

Example HTML code 1:

This example illustrates the use of the deleteFromDocument method:
<head>
    <script type="text/javascript">
        function RemoveSelection () {
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selection = window.getSelection ();
                selection.deleteFromDocument ();
            }
        }
    </script>
</head>
<body onmouseup="RemoveSelection ();">
    Select some content on this page with the mouse!
</body>
Did you find this example helpful? yes no

Example HTML code 2:

A cross-browser solution for the previous example:
<head>
    <script type="text/javascript">
        function RemoveSelection () {
            if (window.getSelection) {  // all browsers, except IE before version 9
                var selection = window.getSelection ();
                selection.deleteFromDocument ();

                    /* The deleteFromDocument does not work in Opera.
                        Work around this bug.*/
                if (!selection.isCollapsed) {
                    var selRange = selection.getRangeAt (0);
                    selRange.deleteContents ();
                }

                    // The deleteFromDocument works in IE,
                    // but a part of the new content becomes selected
                    // prevent the selection
                if (selection.anchorNode) {
                    selection.collapse (selection.anchorNode, selection.anchorOffset);
                }
            } 
            else {
                if (document.selection) {    // Internet Explorer
                    document.selection.clear ();
                }
            }
        }
    </script>
</head>
<body onmouseup="RemoveSelection ();">
    Select some content on this page with the mouse!
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content