Check if a div contains a number

Asked

Viewed 236 times

4

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

Look at:

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

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

  • 1

    and if the following happens: <a href="#">a1</a>?

  • Hello, actually in my case there is no such possibility... Can only have text or numbers, not numbers with texts!

3 answers

11


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

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

UPDATE

You can use cache 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");
});

Follows jsFiddle of the original and the version with cache

5

One simple way to achieve this is by using the native function isNaN javascript:

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

Example: FIDDLE

  • 1

    Well remembered, I used the native function of jQuery because I saw that he used the library. Most likely, internally, she uses that same method.

5

You already have some very good answers, I’m just going to suggest a force to create a collection of objects based on the intended verification, to streamline your practical scenario:

Example in Jsfiddle

// 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 formatting of the link:

Captura de Tela


By evolving the practical use of this code, we can involve it in a function that allows us to make use of this method for other scenarios:

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

This way you can pass the desired selector and Regexp to be used.

  • Elegant and high-level. I consider your response to be the best.

  • I actually voted for your answer and @Kazzkiq’s because they both solve the author’s problem. I just wanted to leave something more pliable in terms of use. But I’m glad you liked it!

  • Not only did I like it but I learned something new.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.