Search code examples
javascripttextcursorrangeselection

How to get text from selected text to end of page


I want to get all text from the selected text to end of page, that mean just the text we see on page. But when i try this, it also get text in tag 'script', 'noscript'... and other tags which not show on page:

function getTextFromCursor(){
    count=0;
    var allText ="";
    if(window.getSelection){
        var selection = window.getSelection();
        var selRange = selection.getRangeAt(0);
        var range = document.createRange();     
        range.setStart(selRange.startContainer, selRange.startOffset);
        var theBody = document.getElementsByTagName('body')[0];
        var lastEl = theBody.lastElementChild;
        range.setEndAfter(lastEl);      
        allText = range.toString();
    }
    return allText;
}  

How could i only get the text which show on page ?


Solution

  • The TextRange module of my Rangy library could help. It allows you to work on text as the user sees it on the page, more or less. With it, your example could be achieved with

    function getTextFromCursor() {
        var selection = rangy.getSelection();
        var selRange = selection.getRangeAt(0);
        var range = rangy.createRange();
        range.selectNodeContents(document.body);
        range.setStart(selRange.startContainer, selRange.startOffset);
        return range.text();
    }