danielemm
danielemm

Reputation: 1696

Apply span to selected text in javascript

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?

Upvotes: 0

Views: 983

Answers (1)

Tim Down
Tim Down

Reputation: 324597

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.

Upvotes: 1

Related Questions