[英]select text inside h1 - javascript
Hi Im trying select the text inside my h1 title. 嗨,我正在尝试选择h1标题内的文本。 My code:
我的代码:
<html>
<h1 id="myText">TextToSelect</h1>
</html>
<script>
var text = document.getElementById("myText");
text.select();
</script>
example: enter image description here 示例: 在此处输入图片描述
There's no such function called select()
in the HTMLElement Object HTMLElement对象中没有称为
select()
函数。
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 有关更多信息,请访问Range对象上的MDN文档。
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 您在DOM中获得了对您的h1标签的引用,但是要提取选择值不起作用,请使用innerText
like this: 像这样:
h1Element.innerText;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.