0

Is it possible to select specific text inside a div using the code. I have a div of text, and I need to iterate through each word selecting it individually, then deslecting and onto the next word.

I'm not talking about simulating a select by changing the background css of the words requiring highlighting, but actually selecting it so the outcome is the same as if the user used the mouse to select it.

I know it's possible inside a text area input, but is it possible on a Div?

------------------------UPDATE------------------------------------------

Ok this is where I'm at with it after having another look at it today. I can select all the text in a span, but not specifically a range of words within that span. The closest I have come ( code shown below... ) is selecting the range manually, then removing the selection, then reapplying it.

<div contentEditable = 'true' id="theDiv">
A selection of words but only from here to here to be selected
</div>
<script type="text/javascript"> 
setInterval( function() {
    var currSelection = window.getSelection();
    var storedSelections = [];

    if ( currSelection ) {
        for (var i = 0; i < currSelection.rangeCount; i++) {
            storedSelections.push (currSelection.getRangeAt (i));
        }
        currSelection.removeAllRanges ();
    }

    if ( storedSelections.length != 0 ) {
        currSelection.addRange( storedSelections[0] )
    } 
}, 1000 );
</script>

The stored selection range object has a startOffset and endOffset property. My question is how do I set this alongside the initial selection via the code ( not via a mouse select ) ?

Michael
  • 59
  • 7

2 Answers2

0

Please read this article, it's difficult to summarise, so better read it:

http://www.quirksmode.org/dom/range_intro.html

This answer here can be useful too:

Can you set and/or change the user’s text selection in JavaScript?

Community
  • 1
  • 1
Reflective
  • 3,100
  • 1
  • 10
  • 21
0

Turns out it's fairly straightforward...

<div id = "theDiv">adsf asdf asdf asdf</div>

<script type="text/javascript">
    var theDiv = document.getElementById('theDiv')
    theDivFirstChild = theDiv.firstChild;
    var range = document.createRange();
    range.setStart( theDivFirstChild, 2 );
    range.setEnd( theDivFirstChild, 8);
    window.getSelection().addRange(range);
</script> 
Michael
  • 59
  • 7