1

Is it possible to apply css or wrap tags around savedRange text selection. I'm using jquery.

this doesn't work:

$(savedRange).css(...);
$(savedRange).wrap(...);
user229044
  • 232,980
  • 40
  • 330
  • 338
Hussein
  • 42,480
  • 25
  • 113
  • 143
  • 1
    When you make a text selection, carets gets placed on both sides of the selection to reference where the selection begins and where it ends. This information is saved in savedRange variable to later reference what was selected. – Hussein Feb 03 '11 at 20:46

3 Answers3

1

If by "savedRange" you mean something like this:

selection = window.getSelection()
savedRange = selection.getRangeAt(0)

Then you will have to create a wrapper for the range first, like so:

wrapper = document.createElement('span')
savedRange.surroundContents(wrapper)
selection.selectAllChildren(wrapper)

You can then apply style:

$(wrapper).css(...)
Matt Zukowski
  • 4,469
  • 4
  • 37
  • 38
0

It won't work around selected text but this would put an HTML tag with some style in it around another HTML element.

$(savedRange).wrap('<span style="color:red" />');
JPB
  • 255
  • 1
  • 5
  • 16
0

just use this:

var sel = window.getSelection();
var range = sel.getRangeAt(0);
var tag = range.commonAncestorContainer.parentElement;

$(tag).css({'color':'red'});
// you can add css again using jquery

hope can help .

Arash Younesi
  • 1,671
  • 1
  • 14
  • 23