goldo11
goldo11

Reputation: 21

Selecting numbers with jQuery

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 ?

Upvotes: 2

Views: 704

Answers (3)

PleaseStand
PleaseStand

Reputation: 32082

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);

Upvotes: 2

pinkfloydx33
pinkfloydx33

Reputation: 12739

You'd have to use regular old javascript. Perhaps use a regular expression to find all numbers and replace them with span tags wrapped around them.

var str = "some text 123"
str = str.replace(/(\d+)/g, "<span>$1</span>");

you'd replace "str" with the contents of some elements. So let's say you wanted to do this over all

elements in your page

$('p').each(function(){ 
    var str = $(this).text();
    str = str.replace(/(\d+)/g, "<span>$1</span>"); 
    $(this).text(str);
 }

edit: you all type too fast

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630389

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.

Upvotes: 1

Related Questions