Javascript Event How to - Apply getSelection() to just a certain element








Question

We would like to know how to apply getSelection() to just a certain element.

Answer


<!DOCTYPE html>
<html>
<body>
  <div>Hi, this is text of some kind. Double click here</div>
  <p>Lorem ipsum...</p>
  <span id="output"></span>
    <script type='text/javascript'>
    function getSelectedText() {<!-- w w  w.  j  a  va 2  s  .c  o m-->
        if (window.getSelection) {
            return window.getSelection().toString();
        } else if (document.selection) {
            return document.selection.createRange().text;
        }
        return '';
    }
    var b = document.getElementsByTagName('body')[0],
        o = document.getElementById('output');
    b.onmouseup = function(e){
        var selText = getSelectedText(),
            targetElem = e.target.tagName.toLowerCase();
        if (selText && targetElem == 'p') {
            o.textContent = 'You selected the text: "' + selText + '" from a ' + targetElem + ' element.';
        }
    };
    </script>

</body>
</html>

The code above is rendered as follows: