Change character color

I have the following HTML code:

<p> <label>* Name</label> </p> <p> <label>* Last Name</label> </p> <p> <label>Mascot Name</label> </p> 

Is it possible to change color only with the * character using jQuery? I tried with the find() function, but I repeat all the characters on the shortcut.

+6
source share
4 answers

If you insist on a solution scenario:

 $("p > label:contains('*')").each(function () { $(this).html($(this).html().replace("*", "<span class='red'>*</span>")); }); 

Demo

+9
source

You must use css for this to happen. Use instead

 <label><span style="color:red">*</span> Name</label> 

This will do the job.

+3
source

I think I would solve it CSS wisely:

 label:first-letter { color: #ff0000; } 

Example here

0
source

Karim's answer is wonderful, but when implementing it, I noticed that he will select only one character in each tag

therefore in this case:

 <p> <label>* Name</label> <label>* Last Name</label> <label>Mascot Name</label> </p> 

he will not work. There is no problem if you replace the selector with "label: contains ('*')" in this case, but what if you want to change the color (or other properties) of an instance of each of this particular character? So in this case:

 <p> * Name<br/> * Last Name<br/> Mascot Name </p> 

you really need something else (I know this doesn't look good, but this is the actual output from Wordpress). I found this: Change the formatting of a specific character using css or jquery , where the Blazemonger answer does the trick! I will repeat it here:

 $('selector').html(function(i,el) { return el.replace(/\*/g, '<span class="color">*</span>'); });​ 
0
source

Source: https://habr.com/ru/post/906113/


All Articles