views:

230

answers:

0

I need to split a span into two spans wherever the user clicks. The following jQuery works fine in Firefox:

$(function () {
    $('span.sentence').click(add_sentence);
});

function add_sentence() {
    var selection = window.getSelection();

    if (selection) {
     var anchor, t1, t2;

     anchor = selection.anchorNode;
     parent_sentence = anchor.parentNode;

     //if (this != parent_sentence) return false;

     text = anchor.nodeValue;

     t1 = jQuery.trim(text.substring(0, selection.anchorOffset));
     t2 = jQuery.trim(text.substring(selection.anchorOffset, text.length));

     if (parent_sentence && t1.length > 0 && t2.length > 0) {
      var sentence1, sentence2;

      sentence1 = document.createElement("span");
      $(sentence1).addClass("sentence");
      $(sentence1).text(t1);

      sentence2 = document.createElement("span");
      $(sentence2).addClass("sentence");
      $(sentence2).text(t2);

      $(sentence1).insertBefore(parent_sentence);
      $(sentence2).insertAfter(parent_sentence);

      $(parent_sentence).remove();
     }
    }
}

I'm trying to do the same with document.selection and TextRange in IE, but nothing seems to work. Every resource I've found refers to TextArea selections. Any ideas?