0

I would to apply a span class to selected text on browser window in Javascript (like an highlight feature).

I've tried with

function replaceSelectedTextWithHTMLString(newstring) {
    var range = window.getSelection().getRangeAt(0);
    range.deleteContents();
    range.innerHTML = newstring;
}

but it does not work. If i try to insert as newstring= "< span = "myspan" > text < / span >" I can't look anything and the 'text' does not appear. Seems it does not like the HTML code. How can I solve it?

Tim Down
  • 318,141
  • 75
  • 454
  • 536
danielemm
  • 1,636
  • 1
  • 14
  • 24
  • @Andy: That question was confusing: the OP seemed to want textarea-based solutions initially, so it hasn't had answers that would apply to this question. – Tim Down Feb 09 '11 at 10:06
  • @Tim: oh yeah, I see that now. Hopefully the close vote will go ignored by people who read more carefully than me... – Andy E Feb 09 '11 at 10:09

1 Answers1

1

How easy this is depends on what exactly you need to achieve. If all you need is basic highlighting using a background colour, your best bet is document.execCommand(). See the following for code to do this: Change CSS of selected text using Javascript

If you need to apply more styling than document.execCommand() can provide (there are also various other formatting commands for things like bold and italic, but the markup this produces varies between browsers and isn't always CSS based), it's much trickier: in general, you need to surround every text node within the selection in a span with the desired class. I would suggest using Rangy and its CSS class applier module to do this in a cross-browser way. Disclaimer: this is a plug for my own library.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536