Friday, May 22, 2015

Next TEXT node in a HTML DOM

The Rangy tool is great for making cross-browser HTML selections. It has this useful function "surroundContents", which pastes in a span around the text of the selection. But it refuses to work if the selection crosses an element boundary. It's so stupid, because there is a perfectly sound way to wrap all the text elements in one selection, which is what I wanted. I was trying to implement a commenting tool, which adds a comment to an arbitrary selection in HTML. So the range needs to be coloured and have something to activate it when the user clicks on it. To do that I can't accept rangy's restriction on surroundContents. So I wondered if I could write a simple function that would wrap ANY text elements in the current selection with <span class="someclass">...</span>. It turns out it was pretty easy, although I couldn't find anything on the Web by searching. Here's my test code. If you check the HTML you'll see that it works when going up, down or across the DOM tree. According to the specs this works on any browser. This is a HTML DOM thing, so not much point converting it to jQuery. It should ideally be part of Rangy or jQuery, or converted to a jQuery plugin.

No comments:

Post a Comment