selecting text by ignoring inner Elements of div tag javascript
Posted
by sugar
on Stack Overflow
See other posts from Stack Overflow
or by sugar
Published on 2010-06-01T13:17:40Z
Indexed on
2010/06/01
13:23 UTC
Read the original article
Hit count: 197
<html>
<body>
<script language="javascript">
function getSelectionHTML()
{
var div = document.getElementById("myDiv").childNodes;
if (document.createRange) {
var textNode=div.firstChild;
var rangeObj=document.createRange();
rangeObj.setStart(textNode,0);
rangeObj.setEnd(textNode,10);
selRange.collapse(true);
var elem = document.getElementById('myDiv')
elem .innerHTML = elem .innerHTML.replace(rangeObj.toString(), '<span style="background-color: lime">'+rangeObj.toString()+'</span>')
}
}
</script>
<div id="myDiv">
asdf as<b>dfas df asf asdf sdfjk dvh a sjkh jhcdjkv</b> iof scjahjkv ahsjv hdjk biud fcsvjksdhf k
</div>
<form name="aform">
<input type="button" value="Get selection" onclick="getSelectionHTML()">
</body>
</html>
Ok. Let me explain -> getSelectionHTML() method is for selection of characters from 0 to 10. I am getting the values by "myDiv" id. but inner bold, italic & other tags are putting me in trouble.
In simple words, I just want to make selection of first ten characters (& apply them span tag) which are in "myDiv" tag.
What exactly I am missing ? Can anyone help me ?
Thanks in advance for sharing your knowledge.
Sagar.
© Stack Overflow or respective owner