Reputation: 1485
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 the color only to the character *
with jQuery?
I tried with the function find()
but I repeat all the characters on the label.
Upvotes: 7
Views: 12827
Reputation: 11
Karim's answer is great, but when implementing it, I noticed it will only select one character within every
tag, so in this case:
<p>
<label>* Name</label>
<label>* Last Name</label>
<label>Mascot Name</label>
</p>
it wont't work. 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 every instance of that specific character? So in this case:
<p>
* Name<br/>
* Last Name<br/>
Mascot Name
</p>
you really need something else (I know it doesn't look to good, but this is actual output from Wordpress). I found this: Change formatting of a specific character using css or jquery, where Blazemonger's answer does the trick! I'll repeat it here:
$('selector').html(function(i,el) {
return el.replace(/\*/g, '<span class="color">*</span>');
});
Upvotes: 0
Reputation: 2005
I think I would solve it CSS wise:
label:first-letter {
color: #ff0000;
}
Example here
Upvotes: 0
Reputation: 342635
If you insist on a scripted solution:
$("p > label:contains('*')").each(function () {
$(this).html($(this).html().replace("*", "<span class='red'>*</span>"));
});
Upvotes: 12
Reputation: 8532
You should rather use css to make this happen. Use the following instead
<label><span style="color:red">*</span> Name</label>
This will do the work.
Upvotes: 3