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?
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>For convenience, it wraps each character with a range with the corresponding class name, which simplifies the assignment of individual styles.
: , innerHTML, HTML, . .
HTML ( -), , .
( 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>