Paul Phoenix
Paul Phoenix

Reputation: 1433

JavaScript DOM adding a range to window selection object

I am adding a range to a selection object

var selection = window.getSelection();
selection.addRange(range);

upon adding the same range on different pages the properties coming out for selection object are different.

Desired selection Object

Selection {type: "Range", extentOffset: 1, extentNode: div#hiddenarea, baseOffset: 0, baseNode: div#hiddenarea…}

Undesired Selection Object

Selection {type: "Caret", extentOffset: 19, extentNode: text, baseOffset: 19, baseNode: text…}

what does selection type caret means and how can I set it as Range.

As I Explored more I can see the problem is coming when we create selection object initially

var selection = window.getSelection();

Desired

selection: Selection
anchorNode: null
anchorOffset: 0
baseNode: null
baseOffset: 0
extentNode: null
extentOffset: 0
focusNode: null
focusOffset: 0
isCollapsed: true
rangeCount: 0
type: "None"
__proto__: Selection

Undesired

selection: Selection
anchorNode: text
anchorOffset: 19
baseNode: text
baseOffset: 19
extentNode: text
extentOffset: 19
focusNode: text
focusOffset: 19
isCollapsed: true
rangeCount: 1
type: "Caret"
__proto__: Selection

Upvotes: 1

Views: 1030

Answers (1)

cjnahine05
cjnahine05

Reputation: 203

Try this one bro.

<script type="text/javascript">
    function SelectFirstLine () {
        var elemToSelect = document.getElementById ("firstLine");
        if (window.getSelection) {  // all browsers, except IE before version 9
            var selection = window.getSelection ();
            var rangeToSelect = document.createRange ();
            rangeToSelect.selectNodeContents (elemToSelect);

            selection.removeAllRanges ();
            selection.addRange (rangeToSelect);
        } else {
            if (document.body.createTextRange) {    // Internet Explorer
                var rangeToSelect = document.body.createTextRange ();
                rangeToSelect.moveToElementText (elemToSelect);
                rangeToSelect.select ();
            }
        }
    }
</script>

hope it helps you with that :)

Upvotes: 1

Related Questions