开发者

Selecting numbers with jQuery

In a given DIV I 开发者_C百科wish to apply a SPAN to all numbers and only them. Is there a way to select numbers with jQuery ?


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜