Failed to execute surroundcontents on selection containing span tag

Failed to execute surroundcontents on selection containing span tag

I am trying to color the background of a user text selection with two colors according to his choice with the option to change the color of an already colored selection. I use jquery and html to generate span tag . the problem I encounter is when the user want to change a already colored selection example:

colored selection text0 text1 text2 text3 with color1

 <span class= color1> text0 text1 text2 text3 </span> text4 text5 text6 

user select text2 text3 text4 to color it with color2, this

 var newNode = $('<span class="color2" />')[0]; SelRange.surroundContents(newNode);

return Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node.