Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript selectionStart & selectionEnd

I'm having some difficulties getting the script below to work with my text editor. I'm not sure what is wrong but selectionStart and selectionEnd are returning as undefined.

Its suppose to get highlighted text in an editable iframe and then replace it.

 var textarea = document.getElementById('editor').contentWindow.document.body.innerHTML;

 if (document.selection)
 {
  textarea.focus();
  var sel = document.selection.createRange();
  alert(sel.text);
  sel.text = '<b>' + sel.text + '</b>';
 } else {
  var len = textarea.length;
  alert(len);
  var start = textarea.selectionStart;
  alert(start);
  var end = textarea.selectionEnd;
  alert(end);
  var sel = textarea.substring(start, end);
  alert(sel);
  var replaced = '<b>' + sel + '<b>';
  textarea =  textarea.substring(0,start) + replaced + textarea.substring(end,len);
 }
like image 659
Cory Avatar asked Oct 19 '25 13:10

Cory


1 Answers

The reason selectionStart and selectionEnd are undefined is that your textarea variable contains a string, not a reference to a <textarea> element. You seem to be aware of this since elsewhere you're calling string methods such as substring. Just to be clear, strings have no selectionStart and selectionEnd properties; the objects that do are textareas and text inputs.

like image 107
Tim Down Avatar answered Oct 21 '25 03:10

Tim Down