Here a...">

How can I draw specific letters in the text of an html element?

I have a few spanwith some words in it, for example

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

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

I’m thinking about taking span.innerText property, removing the text node from the span element and adding a few more spaces inside (or instead of) and giving them the necessary style.

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

+4
source share
6 answers

You can do this 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>
Run codeHide result

For convenience, it wraps each character with a range with the corresponding class name, which simplifies the assignment of individual styles.

: , innerHTML, HTML, . .

HTML ( -), , .

+7

( dfsq), :

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>
Hide result

: http://jsfiddle.net/e6c3yy0j/

+2

, javascript:

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

jsfiddle

+1

, 'e', fontcolor.

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;

Fiddle

+1

( , :first-letter). , - . A span , FontAwesome i .

, , :

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

CSS:

.phrase i {
    font-style: normal; /* Because I is italic by default */
    color: red;
}
0

, , javascript:

HTML

<span id="phrase">H<span class="my-class">e</span>r<span class="my-class">e</span> ar<span class="my-class">e</span> som<span class="my-class">e</span> words</span>

CSS

.my-class {
    color: red
}
-1

All Articles