ContentSelect

A JavaScript library providing cross-browser support for content selection.

Selecting content in a browser using JavaScript used to be a much more complex problem (I'm pointing a finger firmly at you IE) but modern browsers now seem to provide a fairly uniform interface for the task - although there are still some challenges.

ContentSelect is designed specifically for selecting in-line content within a block level element, it's not (that I'm aware) capable of selecting content beyond this scope reliably. This design decision is due to the approach I took when designing the content editor where individual blocks are made editable rather than the entire page.

Usage

ContentSelect makes selecting page content or querying the current selection straightforward. Let's assume we have the following block of HTML content:

Whitespace

The eagle-eyed amongst you might have noticed that the paragraph I defined for the usage examples doesn't have any white space between the tags and the content. The reason I did this is that white space affects content selection. For example if we defined our content like so:

To select the first word in the paragraph 'The' we need to create a Range for [4, 7] to account for the extra spacing at the start. This is perhaps not what you'd expect, given that positioning the caret at [0, 0] or [4,4] will for all intents and purpose have the same effect for the user.

My advice, where possible, is to work with whitespace trimmed from either inner end of the containing element.

Self-closing tags

FireFox, Chrome and IE all handle caret position for self-closing tags (such as <br>) differently. To introduce some consistency (and sanity) the prepareElement class method is provided. It wraps empty text nodes around each self-closing tag within an element.

I recommend calling prepareElement before selecting or querying the selection of elements: