1

I am looking into writing a simple code editor for JavaScript. Currently a div with contenteditable seems the more appropriate than a text area. But still it feels very rudimentary in terms of getting cursor div.

<div contenteditable="true">
    <div><br></div>
    <div>123</div>
    <div><br></div>
    <div>abc</div>
</div>

This is a div where I have four lines and I have placed the cursor on line two (<div>123</div>). Is there a way to get the div where the cursor is present, efficiently? My current method is

var xpath = "//div[text()='123']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;

I want to insert a new div after the obtained div, which I do as follows:

var d = document.createElement("div")
var b = document.createElement("br")
d.appendChild(b)
matchingElement.parentNode.insertBefore(d, matchingElement.nextSibling);

Here the problem is if the text in the div is large, wouldn't it lead to performance issues while doing a string comparison on every dom element?

John Doe
  • 2,225
  • 6
  • 16
  • 44
  • 1
    See this question: https://stackoverflow.com/questions/31093285/how-do-i-get-the-element-being-edited It may not address finding _nested_ contentEditable elements when the cursor is sitting passively, but if events are being triggered (such as `keyup`), or if the element has no contentEditable anscestors, options exist here. – Cat Mar 10 '19 at 06:54
  • Actually, even if neither of the above conditions is met, you could fire a custom event that triggers the solution from the accepted answer to that question. – Cat Mar 10 '19 at 07:05

0 Answers0