Here is some HTML that I am working with in my UIWebView:
<div id = "1">
<span style = "background-color:red">
<a href = "10&20">
This is a link
</a>
</span>
</div>
Once the link is tapped, I want to programmatically select the link text in the UIWebView (so "This is a link" would now be highlighted with the blue iOS text selection tool). This is why I am sending some range information in the href of the a tag. This is the call I am using to try and make this programmatic selection:
//set content editable true
[self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"selectElementContentsInRange(document.getElementById('1'), 10, 20)"]];
And this is the javascript function:
function selectElementContentsInRange(el, first, second) {
var range = document.createRange();
alert("Makes it here");
range.setStart(el.firstChild, first);
alert("Doesn't make it here");
range.setEnd(el.firstChild, second);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
And as you can see with the alerts, it doesn't make it past the range.setStart()
call without throwing an error. The Safari javascript debugger is giving me this error:
IndexSizeError: DOM Exception 1: Index or size was negative, or greater than the allowed value.
I have tried so many different things, and nothing is working. I am completely at my wits end and would really appreciate some insight into how to do this. I am beginning to doubt that it is even possible to programmatically select text in UIWebView. Am I wrong? Has anyone done this?