0

I am trying to select/Highlight all tds in a table (for copying) using following code but I am getting this error

Failed to execute 'selectNode' on 'Range': parameter 1 is not of type 'Node'.

can you pls let me know what I am doing wrong here?

function selectElementContents(el) {
    var body = document.body, range, sel;
    if (document.createRange && window.getSelection) {
        range = document.createRange();
        sel = window.getSelection();
        sel.removeAllRanges();
        try {
            range.selectNodeContents(el);
            sel.addRange(range);
        } catch (e) {
            range.selectNode(el);
            sel.addRange(range);
        }
    } else if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
}

$("#select").on("click", function(){
  selectElementContents($("#table"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" border=1>
    <thead>
        <tr><th>Heading</th><th>Heading</th></tr>
    </thead>
    <tbody>
        <tr><td>cell</td><td>cell</td></tr>
    </tbody>
</table>

<input type="button" value="select table" id="select" />
Behseini
  • 6,066
  • 23
  • 78
  • 125

1 Answers1

2

You currently pass in a jQuery collection when you call selectElementContents:

selectElementContents($("#table"));

Instead you should pass in an actual node.

selectElementContents($("#table").get(0));
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52