How to get a loose number in my HTML?

8

Consider the following code:

<span class="test"><span style="color:green">Teste</span>:</span> Text<br><br>
<span class="test"><span style="color:green">Mais</span>:</span> Text<br><br>
<span class="test"><span style="color:green">Número</span>:</span> 250<br><br>

How do I separate that number (250) next to the word "Number" to be treated later in Javascript? I think it's possible with regular expressions, but I could not make the effect ...

The span can repeat infinitely, and I need to look for the number that comes soon after.

    
asked by anonymous 22.04.2014 / 00:49

2 answers

8

You can traverse the DOM instead of using regex, it's much faster to process. Do the following:

  • Find the <span> that contain "Número" and for each:
  • Access the parent node of it ( parentNode ) and grab the next node ( nextSibling )
  • Convert the value to number and save it somewhere.
  • The code below does this:

    var rotulos = document.querySelectorAll('.test span'), rotulo;
    var valores = [], valor, node;
    for(var i=0; i<rotulos.length; i++) {
        rotulo = rotulos[i].textContent || rotulos[i].innerText;
        if(rotulo === 'Número') {
            node = rotulos[i].parentNode.nextSibling;
            valor = node.textContent || node.innerText;
            valores.push(Number(valor));
        }
    }
    // valores agora contém os números
    

    Demo

        
    22.04.2014 / 04:55
    4

    Hello, Considering that the code of the spans is directly inside the body, it would look like this:

    var html = document.body.innerHTML;
    var regex = /<\/span> ([0-9]+)/g;
    var resultados;
    //Itera por todas as correspondências do número
    while(resultados = regex.exec(html)){
        console.log(resultados[1]);
    }
    

    The exec method returns an array with matches in addition to the groups captured by the syntax in parentheses ( link ). In the sixth line we take the first group, which corresponds to the number, in index 1.

        
    22.04.2014 / 05:02