Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 141307

How can I color specific words on content editable element?

$
0
0

I am trying to make a coding editor, my problem is I want to color specific words on a content editable div for example if the user wrote this code: function print(){}; function load(){}; the word "function" should be colored red.

Here's what I have tried, unfortunately it does not work but I wanted to show effort and the idea of what I'm trying to accomplish.

let editor = document.getElementById("editor");

editor.oninput = () => {
    editor.innerHTML = colorWord(editor.innerHTML, "function");
    caretAtEnd(editor);
}

function colorWord(text, word) {
    while (text.includes(word)) {
        text = text.replace(word, "<span style='color:blue;'>" + word + "</span>");
    }
    return text;
}

function caretAtEnd(element) {
    element.focus();
    if (typeof window.getSelection != "undefined"&&
        typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(element);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(element);
        textRange.collapse(false);
        textRange.select();
    }
}

Viewing all articles
Browse latest Browse all 141307

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>