+ 2

[SOLVED] How to get the index of the selected text in a contenteditable div?

The title is pretty self-explanatory. I tried using div.selectionStart, but it only works for inputs and textareas. I know that one way would be to find the index of the selected text, but it won’t work if the selected text is repeated earlier in the div. Do you know any way to do it? Thanks in advance.

20th Feb 2019, 6:13 AM
Rowsej
Rowsej - avatar
10 Answers
+ 2
Like, when you call this, it returns object with selection. More info: https://developer.mozilla.org/cs/docs/Web/API/Window/getSelection
3rd Apr 2019, 5:09 AM
Maneren
Maneren - avatar
+ 6
Maneren Thanks for that link!
3rd Apr 2019, 5:45 AM
Rowsej
Rowsej - avatar
+ 5
Maneren Can you please give an example?
2nd Apr 2019, 8:54 PM
Rowsej
Rowsej - avatar
+ 3
So, i ran out of ideas Only that with css
20th Feb 2019, 7:11 AM
Maneren
Maneren - avatar
+ 2
What do you want to do with the text after it is selected, for something you can use css selectors
20th Feb 2019, 6:27 AM
Maneren
Maneren - avatar
+ 2
In css, and now i got an idea, in javascript, one can use querySelector() with div::selection selector, am i right?
20th Feb 2019, 6:39 AM
Maneren
Maneren - avatar
+ 1
Maneren Not sure. I just think it would be useful knowing how to get the selection index.
20th Feb 2019, 6:29 AM
Rowsej
Rowsej - avatar
+ 1
Hmm... I think that the querySelector function gets elements, whereas the selected text would only be part of an element, not the whole thing.
20th Feb 2019, 7:00 AM
Rowsej
Rowsej - avatar
+ 1
window.getSelection(); should do the trick
2nd Apr 2019, 2:58 PM
Maneren
Maneren - avatar
+ 1
You're welcome
3rd Apr 2019, 11:03 AM
Maneren
Maneren - avatar