Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select numbers on a page with jQuery or Javascript

I'm just wondering if there's a way to locate numbers on a page with jQuery or plain Javascript.

Here's what I want to do:

Say "June 23" is on the page. What I want to do is be able to prepend and append some <span> selectors to the number.

Using :contains() with jQuery selects the whole thing, not just the number.

These strings are being generated without any wrapping elements by a Wordpress theme I'm working on, and I only want to select the number.

Any help would be appreciated! Thanks for even thinking about it.
-George

like image 751
ggwicz Avatar asked Jun 25 '11 22:06

ggwicz


1 Answers

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.

like image 127
user113716 Avatar answered Oct 16 '22 10:10

user113716