I am pretty new to JQuery. I have a text in a div. When the user double clicks a word, I want to select all word's appearances. The problem is that I don't know how to refer to the selected word. Can anybody help me? Thanks in advance
Asked
Active
Viewed 1,271 times
4 Answers
4
This seems to work: http://jsfiddle.net/f3wzT/
The code finds the double-clicked word and then wraps all instances of the word in a span. There might be a better way to do it but, as you can see from the jsFiddle above, this does work.
Here's the code (quickly cobbled together from multiple sources):
<script type="text/javascript">
function getSelectedText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.getSelection) {
txt = document.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
return txt;
}
function deselectText() {
if (window.getSelection) {
window.getSelection().removeAllRanges();
} else if (document.getSelection) {
txt = document.getSelection().removeAllRanges();
} else if (document.selection) {
txt = document.selection.empty;
}
}
$(document).ready(function() {
$('#content').dblclick(function() {
$('.highlight').removeClass('highlight');
var t = getSelectedText();
var regex = new RegExp(t, "gi");
this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"highlight \">" + matched + "</span>";});
deselectText();
});
});
</script>

NakedBrunch
- 48,713
- 13
- 73
- 98
1

mbx-mbx
- 1,765
- 11
- 23
-
that seems to work with a linked word. Doesnt seem to actually do what the OP wants. – Laurence Burke Dec 02 '11 at 15:18
-
You might be able to adapt it by putting every word in the DIV in a 'linked word' and styling it so it doesn't looked like a linked word. – mbx-mbx Dec 02 '11 at 15:19
-
You could put every word in that div in an tag (not pretty I know) and then put a delegate on the div itself (I believe this is now called 'On' in the latest version of jquery) which can pass the text of the tag to a function which calls highlight on the plugin mentioned above... doesn't seem very elegant though and will result in a lot of html – mbx-mbx Dec 02 '11 at 15:25
0
There is a previous answer to this on stack that can be adapted from using paragraph to div.
You can change the alert to find the text in other places in the document and highlight them.

Community
- 1
- 1

Laurence Burke
- 2,348
- 14
- 26
0
Here is a sample that puts a span around each word and then highlights all spans that have the same text. http://jsfiddle.net/6xsNK/3/
$('.para').each(function() {
var words = $(this).text().split(' ');
var el = $(this).empty();
$(words).each(function(i) {
el.append($('<span>').text(this+' '));
});
});
$('.para span').dblclick(function() {
var t = $(this).text();
var count = $('.para span').removeClass('hilite').filter(function() { return $(this).text() == t;}).addClass('hilite').size();
alert(count+' match(es) found');
});

js1568
- 7,012
- 2
- 27
- 47