Reputation: 25
Hi Im trying select the text inside my h1 title. My code:
<html>
<h1 id="myText">TextToSelect</h1>
</html>
<script>
var text = document.getElementById("myText");
text.select();
</script>
example: enter image description here
Upvotes: 0
Views: 2731
Reputation:
There's no such function called select()
in the HTMLElement Object
To simulate user selection, You can try this :
var element = document.querySelector('#myText');
var range = document.createRange();
range.selectNode(element);
window.getSelection().addRange(range);
<h1 id="myText">TextToSelect</h1>
For more Info Visit the MDN Documentation on the Range Object
Upvotes: 1
Reputation: 296
there is no select to get the text, with this:
var h1Element = document.getElementById("myText");
you get the reference to your h1 tag in the DOM, but to extract the value select doesn't work, use innerText
like this:
h1Element.innerText;
Upvotes: 0