How to store the span tag texts in an array in jquery / javascript?

1

I need to get the text that is contained between the span tags.

This is the framework I'm working on:

<table>
    <thead>
    </thead>
    <tbody>
    <tr>
        <td colspan="9" class="questiontext">
            <p>
                <span>TEXTO A SER COPIADO 1.</span>
            </p>

            <p>
                <span>O objeto de estudo da lógica é:</span>
            </p>
        </td>
    </tr>
    <tr>
        <td colspan="9" class="questiontext">
            <p>
                <span>TEXTO A SER COPIADO 2.</span>
            </p>

            <p>
                <span>É um sistema de normas, princípios e valores...</span>
            </p>
        </td>
    </tr>
    </tbody>
</table>

And this is the code I'm using to fetch but it does not return values like they should:

var quest = document.querySelectorAll('td[class^=questiontext] > p:nth-child(1)');

var valores = [];

for (var i = 0; i < quest.length; i++)
{
    valores.push
    (
        $(quest[i]).find( "span" )
    );
}


console.log(quest);


console.log(valores);

What am I missing?

P.S. I have to get the values because the idea is in the future to take these values to mark the spans with repeated contents.     

asked by anonymous 28.09.2017 / 20:59

1 answer

2

You're using $(divs[i]).find( "span" ) but you're iterating over quest . It should be

$(divs[i]).find( "span" )

In this case you could use native JavaScript with .querySelector()

var quest = document.querySelectorAll('td[class^=questiontext] > p:nth-child(1)');

var valores = [];

for (var i = 0; i < quest.length; i++) {
  valores.push(
    quest[i].querySelector("span")
  );
}

console.log(valores);
<table>
  <thead>
  </thead>
  <tbody>
    <tr>
      <td colspan="9" class="questiontext">
        <p>
          <span>TEXTO A SER COPIADO 1.</span>
        </p>

        <p>
          <span>O objeto de estudo da lógica é:</span>
        </p>
      </td>
    </tr>
    <tr>
      <td colspan="9" class="questiontext">
        <p>
          <span>TEXTO A SER COPIADO 2.</span>
        </p>

        <p>
          <span>É um sistema de normas, princípios e valores...</span>
        </p>
      </td>
    </tr>
  </tbody>
</table>
    
28.09.2017 / 21:02