Check if a div contains a number

4

I have a paragraph that contains multiple links, alternating between words or numbers. I need to do the following check: if the link within the paragraph is any text, it will not do anything with the text, but if this link has a number, it will receive CSS formatting.

See:

<p class="teste"><a href="#">Meu texto</a><a href="#">1</a></p>

In case the number 1 should receive any formatting, and my text does not!

    
asked by anonymous 25.02.2014 / 18:39

3 answers

11

If you have only numbers within the a tag, you can use this:

$("a").each(function() {
    if ($.isNumeric($(this).html())) {
        $(this).addClass("classeCss");
    }
});

UPDATE

You can use caching to make the search more performative (it's always important to worry about it):

var cache = $("a");

$(cache).each(function() {
    if ($.isNumeric($(this).html()))
        $(this).addClass("classeCss");
});

Follow jsFiddle's original and version with cache

    
25.02.2014 / 18:47
5

One easy way to do this is to use the isNaN native Javascript function:

$('a').each(function(){
   var t = $(this);
    if(!isNaN(t.html())){
         t.addClass('sua-classe');
    }
});

Example: FIDDLE

    
25.02.2014 / 18:50
5

You already have some very good answers, I will only suggest a force to create a collection of objects based on the intended verification, to dynamize your practical scenario:

JSFiddle Example

// recolhe elementos que só contém números
var soNumeros = $('a').filter(function() {
   return /^[0-9]*$/.test( $(this).text() );
});

// realiza algo com a colecção de objectos gerada
soNumeros.addClass('bubu');

Result of adding CSS class bubu that changes the link formatting:

Byevolvingthepracticaluseofthiscode,wecaninvolvethesameinafunctionthatallowsustousethismethodforotherscenarios:

Example in JSFiddle

/* Procura elementos que contenham X
 */
function procura (ele, pattern) {
    return ele.filter(function() {
       return pattern.test( $(this).text() );
    });
}

// realiza algo com a colecção de objectos gerada
soNumeros = procura($('a'), /^[0-9]*$/);
soNumeros.addClass('bubu');

In this way you can pass the desired selector and RegExp to be used.

    
25.02.2014 / 19:08