Reputation: 65143
code: http://jsfiddle.net/byHMP/2/
(note: when properly selected, the code will insert a span around the selection and change the background color)
Selection Code:
var html = "";
sel = window.getSelection(); // not sure how many browsers this works on.
var temp = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
curr_range = sel.getRangeAt(i);
temp.appendChild(curr_range.cloneContents());
if (temp.innerHTML.length < MINIMUM_SELECTION_LENGTH) {
return false;
}
var selection = document.createElement("span")
//selection.id = content_hash;
curr_range.surroundContents(selection);
selection = $j(selection).addClass("highlighted");
}
html = temp.innerHTML;
so, right now, it'll only select within elements, and MAYBE if you cover an entire element and the text to the left and right of that...
Maybe I need to find a way to expand to the selection in a certain direction if the tags are unmatched? I just don't know. (Also, I wouldn't know how to do that. I mean, I can expand the selection to the overall parent element (a UL for example, when you just want to select multiple LIs, but I feel that is a bit overkill in most cases)
Upvotes: 2
Views: 4067
Reputation: 8368
The Range#surroundContents
requires all selected elements to have their closest common ancestor element contained in the range. Otherwise, it throws a BAD_BOUNDARY_ERR.
To overcome this issue, you need something like the following.
var node = document.createElement(tagName);
var frag = range.extractContents();
node.appendChild(frag);
range.insertNode(node);
if (!range.collapsed) {
range.removeContents()
}
Upvotes: 2