Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I color specific letters in html element text? [duplicate]

Tags:

javascript

css

I have some span with some words in it, like

        <span id="phrase">Here are some words</span>

I need to color all the 'e' characters red.

I think of taking the span.innerText property, remove text node from span element and add some more spans inside (or instead), and give them necessary style.

Is it the only way, or it could be solved in a more elegant way?

like image 544
Dmitry Samoylov Avatar asked Oct 21 '14 11:10

Dmitry Samoylov


People also ask

How do you color individual letters in HTML?

Make separate elements Another way is creating a text with separate elements by using the HTML <span> tag, which is an empty container. This means that you create a multicolor text by putting each letter in a separate element to define a different color for each letter of your text.

How do I make certain words a color in HTML?

To set the font color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property color. HTML5 do not support the <font> tag, so the CSS style is used to add font color.

How do I make two text colors in HTML?

Steps to add multicolor into text: Add a simple text inside the <div> tag with the required selector. Apply the linear gradient property with any colors of your choice. Apply webkit properties that will fill the text with the gradient background and declare the color property with transparent background.

How do you repeat the same text in HTML?

Use the <span> element instead. There's no <repeat> tag in HTML, unless you use JavaScript to create such an element in order to select that in CSS.


5 Answers

You can surely do it with javascript:

var span = document.getElementById('phrase'),
    text = span.innerHTML.split('').map(function(el) {
        return '<span class="char-' + el.toLowerCase() + '">' + el + '</span>';
    }).join('');
  
span.innerHTML = text;
.char-e {
    color: red;
}
<span id="phrase">Here are some words</span>

For convenience it wraps each character with a span with corresponding class name, which makes it easy to assign individual styles.

Warning: However I would not recommend doing this with large texts because the code above replaces innerHTML it can break your HTML if it contains other nested elements. But for small titles with only text this is not going to be a problem.

If you want to work with more complex HTML markup (with children elements) the function needs to be improved to work recursively on child items text content.

like image 102
dfsq Avatar answered Oct 06 '22 04:10

dfsq


More complex implementation (which contain dfsq code) which keep tags:

function addColor(domNode, color, letter){
	if(domNode.nodeType!=1||!domNode.hasAttribute('edited')){
		if(domNode.nodeType==3){
			var newText=document.createElement('span');    
			newText.innerHTML=domNode.textContent;
			newText.setAttribute('edited', true);
			var text = newText.innerHTML.split('').map(function(el){
			  if(el==letter){
				return '<i style=\"color:'+color+'\">'+el+'</i>';
			  }
			  else{
				return el;
			  }
		  }).join('');
		  newText.innerHTML=text;
		  domNode.parentNode.replaceChild(newText,domNode);
		}
		for(var i=0; i<domNode.childNodes.length;i++){
			addColor(domNode.childNodes[i], color, letter);
		}
	}
} 

addColor(document.getElementById('phrase'), 'red', 'e');
<span id="phrase">Here are <a href="#"> test</a>  some text <p> some text again </p> some woreds</span>

With a fiddle: http://jsfiddle.net/e6c3yy0j/

like image 30
Superdrac Avatar answered Oct 06 '22 04:10

Superdrac


I think it's not so ugly to use javascript :

$(document).ready(function() {
   console.log( "ready!" );
   var text = $("#phrase").html().replace(/e/g, '<span class="red">e</span>');
    $("#phrase").html(text)
});

jsfiddle example

like image 35
Thomas Leduc Avatar answered Oct 06 '22 04:10

Thomas Leduc


You can't target specific letters in a text (except for the first one using :first-letter). So yes, your only option is to wrap them with an element. A span would work, the guys from FontAwesome like to use i instead.

So, for example, you could do this:

<span id="phrase">H<i>e</i>r<i>e</i> are som<i>e</i> words</span>

And add this to your CSS:

.phrase i {
    font-style: normal; /* Because I is italic by default */
    color: red;
}
like image 22
MildlySerious Avatar answered Oct 06 '22 03:10

MildlySerious


Split each character in the string and if the character is 'e', then give the red color using fontcolor function.

Code

var s1 = document.getElementById("phrase");
var str = s1.innerHTML;
var newText = "";
for (var i = 0; i < str.length; i++) {
     if (str[i] == 'e') {
     newText+= str.charAt(i).fontcolor("red");
     }
     else {
        newText += str[i];
    }
}
s1.innerHTML = newText;

Find Fiddle Here

like image 43
Ullas Avatar answered Oct 06 '22 02:10

Ullas