Fork me on GitHub

Wapper (wapər)

Wapper is a JavaScript library to wrap selected text in other elements. Wapper takes a Range object and smartly wraps its contents, here's a quick example:

// Given the document:
// <p>Lorem ipsum dolor sit amet.</p>

var textNode = $$("p")[0].firstChild

var range = document.createRange()
range.setStart(textNode, 6)
range.setEnd(textNode, 11)

// Wrap and return an array of the wrapped elements.
var wrapped = Wapper.wrap(range)
// [<span>ipsum</span>]

// Alters the document like so:
// <p>Lorem <span>ipsum</span> dolor sit amet.</p>

The unit tests demonstrate some of the more complex examples.