How to highlight a given text in TinyMCE?

无人久伴 提交于 2019-12-07 15:18:31

Here is the solution I came up with :

var ed = tinyMCE.activeEditor;
var range = ed.selection.getRng();
range.setStart(textNode, start);
range.setEnd(textNode, end);
ed.selection.setRng(range); 

Where :

  • textNode can be a DOM text node that you can retrieve with getElementById or any other short-hand properties (parent, nextSibling etc)
  • start and end are respectively the beginning and the end of the text you want to select

I prefer this solution because I only use the tinyMCE API. I don't rely on objects and methods that can change (in behavior, in bugs ...) from browser to browser.

Try:

var range = document.createRange();
var start = document.getElementById('tinymce');
//var textNode = start.getElementsByTagName('p')[0].firstChild;
//edited
var textNode = start.getElementsByTagName('your_tag_where_you_have_the_text')[0].firstChild;
range.setStart(textNode, 14);
range.setEnd(textNode, 23);
window.getSelection().addRange(range);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!