javascriptjqueryselection-api

selectionStart for non textarea elements


$(element)[0].selectionStart seems to only work for textareas. Is there an alternative for non textareas

I'm trying to wrap strings within DOM elements in tags (bold, italic...)

Also, how do I undo the wrapping?


Solution

  • This is a tricky area. You need the Selection object and DOM Range. However, IE does this all completely differently to proper browsers.

    Wrapping the selection inside tags is also non-trivial in general: you need to consider all the text nodes within the selection.

    My Rangy library normalizes the Selection/Range API for IE and has a module to apply a CSS class to a selection, which may help you to some degree. I'm also planning to write a more general module for applying other styles to a selection/range.

    Sorry for the shameless self-promotion, but short of writing a lot of code yourself I don't know what else to suggest.