Friday 15 February 2013

javascript - How can I color specific letters in html element text? -



javascript - How can I color specific letters in html element text? -

this question has reply here:

change color of character 4 answers

i have span words in it, like

<span id="phrase">here words</span>

i need color 'e' characters red.

i think of taking span.innertext property, remove text node span element , add together more spans within (or instead), , give them necessary style.

is way, or solved in more elegant way?

you can certainly javascript:

class="snippet-code-js lang-js prettyprint-override">var span = document.getelementbyid('phrase'), text = span.innerhtml.split('').map(function(el) { homecoming '<span class="char-' + el.tolowercase() + '">' + el + '</span>'; }).join(''); span.innerhtml = text; class="snippet-code-css lang-css prettyprint-override">.char-e { color: red; } class="snippet-code-html lang-html prettyprint-override"><span id="phrase">here words</span>

for convenience wraps each character span corresponding class name, makes easy assign individual styles.

warning: not recommend doing big texts because code above replaces innerhtml can break html if contains other nested elements. little titles text not going problem.

if want work more complex html markup (with children elements) function needs improved work recursively on kid items text content.

javascript css

No comments:

Post a Comment