S
S
Sergey Miller2021-06-09 17:27:55
JavaScript
Sergey Miller, 2021-06-09 17:27:55

Get positions of selected text in div contenteditable?

The second day I'm steaming. Decided to ask a question here.

There is:

<div contenteditabled="true" class="editor">text, my text. Get selected text, please help me to get position of selected text</div>


On jquery I'm trying to find the positions (beginning and end) of the selected text. I tried several functions from Google, but I did not find the normal one.

How to get positions? It is necessary in order to wrap the selected text in a tag ...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Miller, 2021-06-09
@blackseabreathe

function changeSelected(){
if (window.getSelection() == '') {
return false;
}
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var span = document.createElement("span");
span.appendChild(selectionContents);
span.setAttribute("class", "selected");
span.style.backgroundColor = "yellow";
span.style.color = "green";
range.insertNode(span);
}

I really don't know if I should adddocument.selection?

G
GrayHorse, 2021-06-09
@GrayHorse

find positions (beginning and end) of the selected text.

window.getSelection();
https://learn.javascript.ru/selection-range

L
Leonid Yakovlev, 2021-06-09
@deleo547

Firstly, fix the mistake, contenteditable will be correct
Secondly , here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question