首页 > 解决方案 > 无法将 setSelectionRange 添加到所选元素

问题描述

我使用“getElementById”选择了输入。在我想向该元素添加“setSelectionRange”方法之后。但是有一个错误“'htmlelement'类型上不存在属性'setselectionrange'”。可能是什么问题呢?

const textfield = document.getElementById("masktextfield")
console.log(textfield)

这就是控制台中显示的内容

在此处输入图像描述

现在添加“setselectionrange”

textfield.setSelectionRange(0,0) // property 'setselectionrange' does not exist on type 'htmlelement'

标签: javascriptreactjs

解决方案


const textfield = document.getElementById("masktextfield");
textfield.focus();
textfield.setSelectionRange(2, 5);
<input type="text" id="masktextfield" value="sathish"/>


推荐阅读