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

Asked

Viewed 63 times

1

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

That’s the structure I’m running through:

<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 search for but doesn’t return the values as 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 take the values because the idea is in the future to take those values to mark the spans with repeated contents.

1 answer

2


You’re using $(divs[i]).find( "span" ) but you’re iterating on quest. Should be

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

and in that 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>

  • Oops! You’re right! So I changed the search variable to quest within the for and added .text() to the code. Therefore, within valores.push( ) was like this: $(quest[i]).find( "span" ).text(). Thanks @Sergio!

  • @Gabrieloliveira could use it too: quest[i].querySelector("span").textContent

  • Yes, really! It worked here! It really needed it. Thank you @Sergio! ;)

Browser other questions tagged

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