1

Is it possible to select text (as if the user dragged his mouse across an HTML word in the browser) with the help of Javascript?

I have some JS code that searches an HTML table for a user's string input. I would then like for this code to select/focus on this word if it is found.

var targetTable = document.getElementById("accountTable");

for (var rowIndex = 1 + searchStart; rowIndex < targetTable.rows.length; rowIndex++)
{
    var rowData = '';
    rowData = targetTable.rows.item(rowIndex).cells.item(0).textContent;
    if (rowData.indexOf(str) != -1)
    {
                //select word and focus on it in user's browser?
    }
}
101010110101
  • 1,940
  • 8
  • 31
  • 42
  • Could you clarify more on what you want to happen? – ryandawkins Mar 01 '13 at 20:50
  • Sure. Imagine you're surfing the web and you want to copy a word. You first have to select the word with your mouse. This is the effect I'm after--I want the user's input string to be "selected" in the HTML table (or highlighted in some way). – 101010110101 Mar 01 '13 at 20:54
  • selectionStart/End only work on editable text (even making a readonly stops it working. What you'd need to do if grab the text from the element and reformat it with CSS styling around the text you wanted to show as selected. – Offbeatmammal Mar 01 '13 at 21:02

3 Answers3

0

You could replace the found string with the same string but inside of a span with a specific class.

For Example if the search term was "alpha":

<td>The alphabet is long.</td>
<td>The <span class="highlighted">alpha</span>bet is long.</td>

An when the search changes you would have to revert all highlighted spans back to plain text.

If you want to actually select using the browsers selection there is a limited way discussed here: Programmatically select text in a contenteditable HTML element?

Community
  • 1
  • 1
zachzurn
  • 2,161
  • 14
  • 26
0

In order to highlight an element by hovering, the easiest way to do this would be to use css.

Example:

You have html code:

<p id="test">Word</p>

CSS File:

#word:hover{ color: #FFFF00; }

That will color the text by hovering the element.

Edit, if you had multiple words... You would want to separate them in an element per word. For example:

<text class="word">each</text><text class="word">word</text><text class="word">is</text><text class="word">selectable</text>  

.word:hover{ color: #FFFF00; }

Here's the JS Fiddle: http://jsfiddle.net/braTe/

ryandawkins
  • 1,537
  • 5
  • 25
  • 38
0

It looks as if you want to use the Selection object. At the basic level you can just set its anchor and focus node and offset, or you can also create a multi-range selection.

Neil
  • 54,642
  • 8
  • 60
  • 72