Change background color of selected text, HTML JQUERY

893 views Asked by At

I recently customize an existing code to segment a plain text into four class by select a part of text then coloring it, after that I retrieve the text of each class to store it in my db, this code http://jsfiddle.net/ouss88/t53wtquf/9/ works well but i want to denied nested span (html tag that determine the class) exemple:

<span class="class1"> text text text </span> ----> accepted
 <span class= class1"> tex <span class="class 2> text  </span> text </span>--> not accepted.

what should i add to this code http://jsfiddle.net/ouss88/t53wtquf/9/

PS: After I select a part of text, i hover the mouse cursor on one of the four class (1.2.3.4) to color the background of the selected text, tou can try by yourself on this link above, i just want to denied embedded class

1

There are 1 answers

1
Gustaf Gunér On

Do something like this, more compact. I think you get the idea.

$('table td').mouseenter(function(){
  $(this).addClass('hilited'+$(this).attr('id'));  
}).mouseleave(function(){
  $(this).removeClass('hilited'+$(this).attr('id'));  
});
.hilited1{color:green}
.hilited2{color:red}
.hilited3{color:blue}
.hilited4{color:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
<tr>
    <tr> <td id="1"> hover on me for Class1 </td> </tr>
    <tr> <td id="2">  hover on me for Class2 </td> </tr>
    <tr> <td id="3">  hover on me  for Class3 </td> </tr>
    <tr> <td id="4">  hover on me  for Class4 </td> </tr>
    
</tr>
</table>