0

I am trying to select a <p> element with the function .select(). I know that you can select text inside an input element, but I have not found a way to select text from other elements.

I have tried document.getElementById(), but it doesn't seem to work.

<p id='test'>Text to select.</p>
<button onclick='copy()'>Click</button>
function copy() {
  var x = document.getElementById('test');
  x.select();
  document.execCommand('copy');
}

I then receive an error message that says 'x.select is not a function.'.

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44

3 Answers3

0

I correctly understood that you need to get the text from the paragraph? In this case, you can do this:

document.getElementById("test").innerText
  • Thank you, but I have tried that method. I still can't seem to select the text, even when using innerTEXT. I appreciate the help, though. –  Jul 30 '19 at 10:12
0

function copy() {
  var x = document.getElementById('test');
  x.select();
  document.execCommand('copy');
}
<input id='test' />
<button onclick='copy()'>Copy to clipboard</button>

The HTMLInputElement.select() method selects all the text in a element or in an element that includes a text field.

You can select and then copy only things that are included in text fields, your text is in a div.

By transforming that div into an input you can copy to clipboard the text that you just inputed into the text field.

See: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
0

Here is the code that can help!!!!!!

<html>
<body>

<p id="foo">
some text <br />
<span>this div is child of p</span>
</p>
<button onclick="selectText('foo');">click me</button>
<script>

function selectText(element) {
    var doc = document;
    var text = doc.getElementById(element);    

    if (doc.body.createTextRange) { // ms
        var range = doc.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) { // moz, opera, webkit
        var selection = window.getSelection();            
        var range = doc.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}
</script>

</body>
</html> 

keep me posted if you need any help...

Niks
  • 110
  • 1
  • 1
  • 10