We have a HTML page. Is it possible to select (by mouse) few words of a paragraph, get reference to those selected words and encapsulate them, say, by the <span>...</span>
tag programatically? We can use jQuery or HTML5/CSS3?
Asked
Active
Viewed 175 times
2

Cartesius00
- 23,584
- 43
- 124
- 195
2 Answers
3
You can use a mouseup
handler and use getSelection
. Say you have a div called testtagging
, then this is a way to add a span to a selected text within that div. See this jsfiddle.
$('#testtagging').on('mouseup',tag);
function tag(e){
tagSelection('<span style="color:red">$1</span>');
}
function tagSelection(html) {
var range, node;
if (document.selection && document.selection.createRange) {
//IE
range = document.selection.createRange();
range.pasteHTML(html.replace(/\$1/,range.text));
return true;
}
if (window.getSelection && window.getSelection().getRangeAt) {
//other browsers
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(
html.replace(/\$1/,range.toString())
);
range.deleteContents();
range.insertNode(node);
}
return true;
}
[edit] adjusted for use with IE too. JsFiddle is also adapted

KooiInc
- 119,216
- 31
- 141
- 177
-
Thank you very much, sounds very good. I'll study this code and let you know. – Cartesius00 Jul 11 '12 at 10:05
0
Propose to wrap all paragraph words into span
elements:
var r = /(\S+)/ig;
var text = $("p").text();
$("p").html(text.replace(r, "<span class='w'>$1</span>"));
Then bind hover/click events:
$("p > .w").on("hover", function()
{
$(this).toggleClass("hover");
})
.on("click", function()
{
$(this).toggleClass("selected");
});
If you want to parse words from selected text range, you should use window.getSelection()
.
Refer to this question or ask me to adapt this code.