I would like to create a function that select a given text inside a HTML element.
For example calling selectText('world') would select world in a markup like <span>Hello </span><strong>world</strong>!
Lots of answers on similar questions suggests to use range and selection but none of them work in my case (some would select all the text, some won't work with such markup, ...).
For now this is what I have (it doesn't work):
function selectText ( element, textToSelect ) { var text = element.textContent, start = text.indexOf( textToSelect ), end = start + textToSelect.length - 1, selection, range; element.focus(); if( window.getSelection && document.createRange ) { range = document.createRange(); range.setStart( element.firstChild, start ); range.setEnd( element.lastChild, end ); selection = window.getSelection(); selection.removeAllRanges(); selection.addRange( range ); } else if (document.body.createTextRange) { range = document.body.createTextRange(); range.moveToElementText( element ); range.moveStart( 'character', start ); range.collapse( true ); range.moveEnd( 'character', end ); range.select(); } } Here is a jsfiddle so you see what is actually happening: http://jsfiddle.net/H2H2p/
Outputed error :
Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': The offset 11 is larger than or equal to the node's length (5). P.S.: no jQuery please :)
setStart(node, offset), and you're getting the offset from the text only, so it's 11, but the textnode you're targeting doesn't have 11 characters, so you end up with an error.Hello woin<span>Hello </span><strong>world</strong>!?