You can walk through all the elements, looking at text nodes, and replacing them with updated content that has the number wrapped.
var regex = /(\d+)/,
replacement = '<span>$1</span>';
function replaceText(el) {
if (el.nodeType === 3) {
if (regex.test(el.data)) {
var temp_div = document.createElement('div');
temp_div.innerHTML = el.data.replace(regex, replacement);
var nodes = temp_div.childNodes;
while (nodes[0]) {
el.parentNode.insertBefore(nodes[0],el);
}
el.parentNode.removeChild(el);
}
} else if (el.nodeType === 1) {
for (var i = 0; i < el.childNodes.length; i++) {
replaceText(el.childNodes[i]);
}
}
}
replaceText(document.body);
Example: http://jsfiddle.net/JVsM4/
This doesn't do any damage to existing elements, and their associated jQuery data.
EDIT: You could shorten it a bit with a little jQuery:
var regex = /(\d+)/g,
replacement = '<span>$1</span>';
function replaceText(i,el) {
if (el.nodeType === 3) {
if (regex.test(el.data)) {
$(el).replaceWith(el.data.replace(regex, replacement));
}
} else {
$(el).contents().each( replaceText );
}
}
$('body').each( replaceText );
Example: http://jsfiddle.net/JVsM4/1/
Note that the regex requires the g
global modifier.
Probably a little slower this way, so if the DOM is quite large, I'd use the non-jQuery version.