Search code examples
javascripttextbackcolor

change backcolor of part of text using javascript?


i have some part of text with html tags , for example

<b>something</b>

i select some part of text for example "some".

with getSelection().getRangeAt(0); i get position of caret (textcursor), so i know which part of text i've selected.

i have startOffset and endOffset. but problem is, that startOffset and endOffset ignores html tags, so numbers which it returns are not bad, and then i don't know on which part of text i have to apply

<span style="background-color: somecolor ">some</span>

any ides how to solve this ? thanks


Solution

  • <b id='str1'>something</b>
    <script>
    function jsReplace()
    {
      var elem = document.getElementById('str1')
      elem .innerHTML = elem .innerHTML.replace('some', '<span style="background-color: somecolor ">some</span>')
    
    }
    </script>