Detailed Method of Inserting Add Text Label Node at Cursor in JavaScript

  • 2021-08-05 08:34:26
  • OfStack

The correct method is to use Selection object and Range object correctly to insert text or node at the current position of cursor. But the two objects are used differently in the IE and standard DOM ways.

Idea: First, get the user's selection (the current position of the cursor can be understood as the selection of starting and ending positions 1). Then, convert from an Selection object to an Range object. The purpose is to insert content by using the method of Range object. Finally, after the insert action is finished, move the cursor behind the insert.


var sel = win.document.selection; //IE 
var sel = win.getSelection(); //DOM 
var range = sel.createRange(); // IE Under  
var range = sel.getRangeAt(0); // DOM Under  
if(range.startContainer){ // DOM Under  
 sel.removeAllRanges(); //  Delete Selection All in Range 
 range.deleteContents(); //  Clear Range Content in  
 //  Obtain Range The first of the 1 A html Node  
 var container = range.startContainer; 
 //  Obtain Range Displacement of starting point  
 var pos = range.startOffset; 
 //  Build 1 Empty Range 
 range = document.createRange(); 
 //  Insert content  
 var cons = win.document.createTextNode(",:),"); 
 if(container.nodeType == 3){//  If so 1 A TextNode 
 container.insertData(pos, cons.nodeValue); 
 //  Change cursor position  
 range.setEnd(container, pos + cons.nodeValue.length); 
 range.setStart(container, pos + cons.nodeValue.length); 
 }else{//  If it is 1 A HTML Node 
 var afternode = container.childNodes[pos]; 
 container.insertBefore(cons, afternode); 
 range.setEnd(cons, cons.nodeValue.length); 
 range.setStart(cons, cons.nodeValue.length); 
 } 
 sel.addRange(range); 
}else{// IE Under  
 var cnode = range.parentElement(); 
 while(cnode.tagName.toLowerCase() !=  " body " ){ 
 cnodecnode = cnode.parentNode; 
 } 
 if(cnode.id && cnode.id== " rich_txt_editor " ){ 
 range.pasteHTML(",:),"); 
 } 
} 
win.focus(); 

The difference between innerHTML and pasteHTML

innerHTML is an attribute. You can get or set the content of HTML in the element. It can be used by any element that can contain child nodes of HTML

pasteHTML () is a method that replaces text or HTML within a specified text area. This method must be applied to an area created by createTextRange () or document. selection. createRange ()


var oRange = document.selection.createRange(); 
 if(oRange.text!=''){ 
 var oHtml = '<a href="#" rel="external nofollow" target=_blank>oRange.text</a>'; 
 oRange.pasteHTML(oHtml); 
 } 

Related articles: