3

I have a regular text node that I just inserted into the DOM.

I'd like to select it (same as if the user physically selected it with his mouse), either with Javascript or Rangy.

I have the following (and I think pretty ugly) code:

        // insert as regular text node
        var txt = document.createTextNode($mySpan.text());
        $myHeading.get(0).insertBefore(txt, $mySpan.get(0));

        // select again
        var sel = rangy.getSelection();
        sel.removeAllRanges()

        var range = rangy.createRange();
        range.selectNode(txt);

I would love any help with this. I have no idea how to implement it, and goggling didn't work. The only way I can think of, is inserting 2 elements between the text, then select it, then remove the elements, but I was wondering if there was a more elegant way.

Thanks, any help appreciated.

nkkollaw
  • 1,947
  • 1
  • 19
  • 29

1 Answers1

5

Unless my eyes deceive me, the only thing missing from your code would be this line:

sel.setSingleRange(range);

Just add it to the end of what you currently have. (You could also remove sel.removeAllRanges().)

Louis
  • 146,715
  • 28
  • 274
  • 320