I have an editable div and multiple blocks of texts between a starting three backticks
and ending three backticks
markers
Let’s say the cursor is anywhere between the markers
Clicking on a button I need to select entire current block
This code works until I type Enter
anywhere inside the current block
Also – I believe there is a shorter version of the code
function get_left(){
let s = window.getSelection();
let range = s.getRangeAt(0);
let so = range.startOffset;
let textNode = range.startContainer;
let textContent = textNode.textContent;
let startPosition = Math.max(so - 4, 0);
let a = textContent.substring(startPosition, so);
return a;
}
function go_left(){
let par = document.getElementById("cstory");
let s = window.getSelection();
let range = document.createRange();
let cp = window.getSelection().getRangeAt(0).startOffset;
let textNode = par.firstChild;
range.setStart(textNode, cp - 1);
range.setEnd(textNode, cp - 1);
s.removeAllRanges();
s.addRange(range);
}
$('button').on('click', async function(){
while(get_left() !== "```n"){go_left();}
let s = window.getSelection();
let range = s.getRangeAt(0);
let story = document.getElementById("cstory").innerText;
let nextXIndex = story.indexOf("n```", range.endOffset);
if(nextXIndex !== -1){
range.setEnd(range.endContainer, nextXIndex);
s.removeAllRanges();
s.addRange(range);
}
});
.cstory{white-space:pre-wrap;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='cstory' id='cstory' contenteditable>
lorem sea
```
lorem ipsum
dolor sit
sky
```
lorem sky
```
lorem ipsum
dolor sit
sky
```
dolor sit
</div>
<br>
<button>CLICK</button>
2
Answers
When you press enter inside the
contenteditable
div, the browser puts the newly created lines inside their own divs, creating new text nodes. The result is thatcp
may not be a position withintextNode
.no additional libraries are needed. plain JS solution here, preventing divs creation and replacing the double quotes so it can work smoothly, as the requirement is to select text which is between backticks, double quotes were disrupting the format and selections were not working