1

First of all, the title is the same as this question: JavaScript Set Window selection

But that question is badly titled since he wants to know how to select or clear the current selection, the answer was how to clear the selection.

The question is, using java-script how can I dynamically/programmatically create a selection on an element (div, p, b, etc.)? Basically how can you dynamically highlight a text inside an element?

There are many answer on how to highlight all text of a particular element, but there are no answer on how to highlight specific text of an element.

Community
  • 1
  • 1
Marl
  • 1,492
  • 2
  • 22
  • 37

1 Answers1

3

From here you can get some of the info: http://quirksmode.org/dom/range_intro.html

EDIT:

You need to traverse the right element node so that you can highlight a specific text inside that element. Therefore, the element in selectParticular(elem, start, end) must be a text element, otherwise an error will occur.

You can highlight/get a selection all text of an element dynamically by using this code:

function selectAll(elem){
   var range = document.createRange();
    range.setStart(elem, 0);
    range.setEnd(elem, 1);
    window.getSelection().addRange(range);
}

You can highlight/get a selection of a particular text on an element by:

function selectParticular(elem, start, end){
    var range = document.createRange();
    range.setStart(elem.firstChild, start);
    range.setEnd(elem.firstChild, end);
    window.getSelection().addRange(range);
}

Note you must see the compatibility table before implementing it to your site

Marl
  • 1,492
  • 2
  • 22
  • 37