I have the following HTML w/Javascript code (note: this only works in Internet Explorer):
<script type='text/javascript'>
function changeIt() {
var startTag = "<span class='h' id='123abc'>";
var endTag = "</span>";
var htmlStr = document.selection.createRange().htmlText;
document.selection.createRange().pasteHTML(startTag + htmlStr + endTag);
}
</script>
<style type='text/css'> .h { background: yellow; }</style>
<p><b>Four</b> score and seven years</p>
<input type='button' value='change' onclick='javascript:changeIt();'>
To use this function, simply highlight any part of the text you see in the screen, then click the "Change" button. Now, the strange behavior:
If you highlight the word "Four" (with the bold tags) with anything else after the Four, it will make the entire highlight bold, which is not what I want. In other words, if you highlight with your mouse:
Four score and seven
then click the "change" button, it will output: Four score and seven
<b><span class='h' id='123abc'><b>Four</b> score and seven</span></b>
I would like it to output this instead: Four score and seven
<span class='h' id='123abc'><b>Four</b> score and seven</span>
What am I doing wrong? I'll take an answer in either Javascript or jQuery.
Note: seems the background color isn't show properly on here, but my point is the whole selection turns bold when I don't want it to.