I wanted to be able to wrap arbitrary text with HTML elements, so I added a wrap
method to my bililiteRange routines. Now I can do something like bililiteRange(el).find(/foo/).wrap(document.createElement('strong'))
and I have instant highlighting!
It obviously can only work if the range is defined on an actual HTML element, not on the text of a <input>
or <text>
element (it throws an error if you try).
For standards-based browsers, there is a simple surroundContents
method that does it in one step. Note that it uses the actual node passed in, so if you need to reuse it, remember to clone it.
IE < 10 doesn't have anything so nice, so I have to hack it by extracting and re-inserting the HTML with htmltext
and pasteHTML
.
It is possible to attempt to create invalid HTML; for instance wrap a range containing a <p>
with a <span>
element. Depending on the browser, this may throw an error or create undefined results.
Leave a Reply