TestProject Forum

Highlight a word or words in a TinyMCE

Hello there,

Is there a way to be able to highlight a word or words in a sentence in TinyMCE?

For example, in the sentence “one two three four five” I would like to be able to highlight the words “two” and “four”.

Thanks!

Hi,
It’s possible using this action execute javascript:

function selectText(selector, inputText){
var el = document.querySelector(selector);
var text = el.firstChild.textContent;
var index = text.indexOf(inputText);

if (index !== -1 ) {
    var range = new Range();

    range.setStart(el.firstChild, index);
    range.setEnd(el.firstChild, index + inputText.length);

    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
}
}
selectText('Element Selector', 'Text To Highlight');

Note:

  1. Replace element selector and Text To Highlight when you call the function.

  2. It will only work as long as you don’t have more than one child element of the selector. i.e as long as the selector leads to the first child of the element.

  3. you need to add context of iFrame to the javascript execution step
    You can do it by simply performing a click inside the TinyMCE and then opening the advanced settings on the step and creating the same context on your Execute Javascript action.

  4. If you change something in the text , making it bold or emphasis for example, it can create more child elements and change your selector. it is best used once. or on different elements.

Many thanks for your reply and support Amit, I will try this and keep you posted!

Have a great day!