skip to Main Content

I have been trying to add text highlighting to python code in a writable div using spans since spans do not work inside textarea, but for some reason the div reverses any text, here’s a simplified version of the code:

<div id="code-editor" spellcheck="false" contenteditable="true"></div>

<script>

    const writableDiv = document.getElementById("code-editor");

    const pythonKeyWords = [ /* has all python keywords */ ]

    const keywordRegex = new RegExp('\b(' + pythonKeywords.join('|') + ')\b', 'g');

    writableDiv.addEventListener('input', () => {
        let text = writableDiv.innerText;
        text = text.replace(keywordRegex, '<span style="color: #f200ff;">$&</span>');
        writableDiv.innerHTML = text;
    });

</script>

Here, if I enter def from the keyword, it comes out as fed in the the div, and vice versa.

I would like to know what’s wrong with what I am doing, because I have tried to use highlights.js and to customize it a bit but it got the same issue as this one.

2

Answers


  1. Please try using textContent instead of innerHTML like this:

    writableDiv.addEventListener('input', () => {
      let text = writableDiv.innerText;
      text = text.replace(keywordRegex, '<span style="color: #f200ff;">$&</span>');
      writableDiv.innerHTML = text;
    }
    
    Login or Signup to reply.
  2. I think this is a problem of design

    If you are trying to create a code editor, you can create it via differents technics, like put an invisible input and then on space key, or enter key, add the word to the editor, like chips elements
    https://material.angular.io/components/chips/examples

    Anyways, I woudl recommend and input element, than a div editor element, those elements are for different purposes. Input type text is the way.

    Another one is to create a input like WYSIWYG but those are ver difficult to create, here are some examples:

    https://onlinehtmleditor.dev/

    Or in your case, search for some library with all this work aready done.

    If you look at the HTML at the time of edit, there are a lot of tricks of constanting generate new html code and printing and hiding inputs elements.

    This is an expensive work, I would recommend an editor that already exists and use it.
    It is a lot of work. Good Luckk!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search