Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select range in contenteditable div

Tags:

I've got a contenteditable div and a few paragraphs in it.

Here's my code:

<!DOCTYPE HTML> <html>     <head>         <meta http-equiv="Content-Type" content="text/html; charset=utf-8">     </head>     <body>         <div id="main" contenteditable="true"               style="border:solid 1px black; width:300px; height:300px">             <div>Hello world!</div>             <div>                 <br>             </div>             <div>This is a paragraph</div>         </div>     </body> </html> 

Assuming, I want to make a range selection which will contain the string "world! This is"

How to do that?

like image 857
angry kiwi Avatar asked Sep 22 '10 17:09

angry kiwi


People also ask

What is Contenteditable div?

Definition and Usage The contenteditable attribute specifies whether the content of an element is editable or not.

How do you make a div Contenteditable?

Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.

How do I stop Enter key in Contenteditable?

To prevent contenteditable element from adding div on pressing enter with Chrome and JavaScript, we can listen for the keydown event on the contenteditable element and prevent the default behavior when Enter is pressed. to add a contenteditable div. document. addEventListener("keydown", (event) => { if (event.


1 Answers

Once you've got hold of the text nodes containing the text you want highlighted, it's easy. How you get those depends on how generic you need this to be. As it is at the moment, before the user has edited it, the following will work:

var mainDiv = document.getElementById("main"); var startNode = mainDiv.firstChild.firstChild; var endNode = mainDiv.childNodes[2].firstChild;  var range = document.createRange(); range.setStart(startNode, 6); // 6 is the offset of "world" within "Hello world" range.setEnd(endNode, 7); // 7 is the length of "this is" var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); 
like image 106
Tim Down Avatar answered Mar 04 '23 00:03

Tim Down