admin管理员组文章数量:1311140
I have this contenteditable element:
<div id="editMe" contenteditable="true">
There is some text here.
<span id="selectThisText">This is the target text.</span>
And some here.
</div>
I want to use Javascript to select (get range object) the contents of #selectThisText. How do I get the range of the content in that element?
Thanks in advance!
I have this contenteditable element:
<div id="editMe" contenteditable="true">
There is some text here.
<span id="selectThisText">This is the target text.</span>
And some here.
</div>
I want to use Javascript to select (get range object) the contents of #selectThisText. How do I get the range of the content in that element?
Thanks in advance!
Share Improve this question edited Nov 21, 2013 at 7:02 tundoopani asked Nov 21, 2013 at 6:48 tundoopanitundoopani 2659 silver badges21 bronze badges3 Answers
Reset to default 11Create a range and use its selectNodeContents()
method.
var span = document.getElementById("selectThisText");
var range = document.createRange();
range.selectNodeContents(span);
This doesn't work in IE <= 8, which doesn't support DOM Range. However, this is one case which is just as easy in old IE:
var span = document.getElementById("selectThisText");
var textRange = document.body.createTextRange();
textRange.moveToElementText(span);
//get Selection
var selection = window.getSelection();
//get Range
var range = selection.getRangeAt(0); //where the range selection happens.
var text = $('#selectThisText').text();
Demo: http://jsfiddle/5NBnP/
本文标签:
版权声明:本文标题:javascript - How do I select (get range or selection object) an element in a contenteditable div if I know the element ID? - Sta 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741874945a2402407.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论