views:

33

answers:

3

Hi,

In a given DIV I wish to apply a SPAN to all numbers and only them. Is there a way to select numbers with jQuery ?

+1  A: 

No, jQuery provides no selector functionality against text nodes...you can loop through the .contents() and manipulate textnodes as you want, but jQuery won't help much here.

For example:

$("div").html(function() { 
  return $(this).text().replace(/(\d+)/g,"<span>$1</span>"); 
});

You can test it out here, note that there are drawbacks to any approach like this, you're changing the .innerHTML which will destroy any event handlers, attached behaviors, etc. Only use this if the content is only text to begin with.

Nick Craver
A: 
pinkfloydx33
A: 

jQuery doesn't provide native selectors for text, but it is possible to achieve that effect. I adapted this from my answer to a previous question, designing it to not mangle any links with numbers in the URL (jsFiddle demo):

function autospan() {
    var exp = /-?[\d.]+/g;

    $('*:not(script, style, textarea)').contents().each(function() {
        if (this.nodeType == Node.TEXT_NODE) {
            var textNode = $(this);
            var span = $('<span/>').text(this.nodeValue);
            span.html(span.html().replace(exp, '<span class="foo">$&</span>'));
            textNode.replaceWith(span);
        }
    });
}

$(autospan);
idealmachine