Coloring A Substring In A Label
I have the following label element where I'd like the asterisk to be colored red. How can this be done using jQuery, or otherwise?
Solution 1:
var label = document.getElementById('labelId');
label.innerHTML = label.innerHTML.replace('*', '<span style="color:red;">*</span>');
No assembly (aka jQuery) required :-)
Solution 2:
you can do it with jQuery if you want
$('#labelId').html( $('#labelId').text().replace('*', '<span style="color:red;">*</span>') );
Solution 3:
If you can change the text, CSS might be a better choice: http://jsfiddle.net/VwLQM/.
label:after {
color: red;
content: "*";
}
Then <label>test</label>
will automatically have a red *
after it.
:after
does not fully work on IE8, so that may be an important thing to consider.
Solution 4:
While this might be a little elaborate, it does give you a little wiggle room to markup red asterisks in elements with more than just text inside of it and will likely give you less trouble in the different browsers.
$(function(){
var elements = $('label');
var markup_element = $('<span class="red">*</span>');
elements.each(function(){
//wrap the element in a jquery object and get it's text stringvar element = $(this);
var element_text = element.text();
//use regex to use the * as a delimetervar other_parts = element_text.split(/\*/);
//empty the element re-add each part programmatically
element.empty();
for( var i = 0; i < other_parts.length; i++ ){
element.append( other_parts[i] );
if( i != other_parts.length - 1 ){
element.append( markup_element );
}
}
});
});
Hope that helps!
Post a Comment for "Coloring A Substring In A Label"