Yes, you will need to wrap the @
in a span
with a class
so that you can change the colour with CSS.
You could manipulate the DOM like this
CSS
.atSign {
color: #f90;
}
HTML
<div id="status">Some @ text <div>that @ contains@what</div>we will@ demonstrate</div>
Javascript
/*jslint maxerr: 50, indent: 4, browser: true */
(function () {
"use strict";
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function getTextNodes(element) {
var nodes = [];
walkTheDOM(element, function (node) {
if (node.nodeType === 3) {
nodes.push(node);
}
});
return nodes;
}
function highlight(element, string, classname) {
var nodes = getTextNodes(element),
length = nodes.length,
stringLength = string.length,
i = 0,
index,
text,
newContent,
span,
node;
while (i < length) {
node = nodes[i];
newContent = document.createDocumentFragment();
text = node.nodeValue;
index = text.indexOf(string);
while (index !== -1) {
newContent.appendChild(document.createTextNode(text.slice(0, index)));
text = text.slice(index + stringLength);
span = document.createElement("span");
span.className = classname;
span.appendChild(document.createTextNode(string));
newContent.appendChild(span);
index = text.indexOf(string);
}
newContent.appendChild(document.createTextNode(text));
node.parentNode.replaceChild(newContent, node);
i += 1;
}
}
highlight(document.getElementById("status"), "@", "atSign");
}());
On jsfiddle
How can you use this with your HTML string you ask?
Javascript
var div = document.createElement("div"),
html;
div.innerHTML = 'Dita Von Teese draagt geprinte 3D-jurk <a target="_blank" href="http://t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a> via @<a target="_blank" href="http://twitter.com/Knackweekend">Knackweekend</a>';
highlight(div, "@", "atSign");
html = div.innerHTML;
console.log(html);
Output
Dita Von Teese draagt geprinte 3D-jurk <a target="_blank" href="http://t.co/s2y6b21S0I">http://t.co/s2y6b21S0I</a> via <span class="atSign">@</span><a target="_blank" href="http://twitter.com/Knackweekend">Knackweekend</a>
On jsfiddle
And no jquery or regexs in sight :)