Search code examples
javascripthtmlcssangularjsjqlite

angular js select all text from a range div and span elements to let user copy the selected text


I am trying to create a select all functionality (in angular js) of some text which appears in a format similar to the structure given below. When all text is selected, then user could hit ctrl + c to copy the same.

<div ="container">
 <div class="header">My example header</div>
  <div class="section1">
    <span>test content1</span>
    <span>test content2</span>
  </div>
  <div class="section2">
    <span>test content3</span>
    <span>test content4</span>
  </div>
  <div class="footer">footer content</div>
</div>

There will be a button, by click on it, all the text appearing inside the container div is required to be selected. I have searched many examples, so far all the examples I found is giving solutions on how to select text from a textarea or textbox. I wanted to find out how do I select all text from such range of html elelments.


Solution

  • Check out this answer: https://stackoverflow.com/a/6150060/2363552

    Here is a plnkr of it working: Plnkr example

    Javascript

    function selectElementContents(el) {
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
    

    HTML

    <div id="container">
        <div class="header">My example header</div>
        <div class="section1">
            <span>test content1</span>
            <span>test content2</span>
        </div>
        <div class="section2">
            <span>test content3</span>
            <span>test content4</span>
        </div>
        <div class="footer">footer content</div>
    </div>
    <button type="button" onclick="selectElementContents(document.getElementById('container'))">Select Text</button>