Fetch content from a td from a class

Asked

Viewed 178 times

0

I have the following lines within a table:

<table id="table_marcas">
    <tr>
        <td>Nome</td>
        <td class="template">Óleos</td>
        <td class="template">Veículos</td>
        <td class="template">Óleos</td>
    </tr>
.....
</table>

These lines are generated dynamically on the server according to some conditions, and may or may not exist in the final HTML. What I’m looking for is to get the contents of class "template", and then check if there is one equal to "Oils".

  • 1

    Could you explain that part of dynamics? Does the table structure change or only the values? It is after page loading or after some event, such as a click on a button?

  • @Randrade, yes the structure can be changed, lines can be removed, or new lines added. It happens during page loading

  • 1

    If it is during loading, the answer code below should suit you.

2 answers

3


You can use getElementsByClassName to search for all elements that have this class, then check its contents:

console.log(verificarElemento('Óleos'));

function verificarElemento(nome) {
  var tds = document.getElementsByClassName("template");
  for (var i = 0; i < tds.length; i++) {
    if (tds[i].innerHTML == nome)
      return true;
  }
  return false;
}
<table>
  <tr>
    <td class="template">Óleos</td>
    <td class="template">Veículos</td>
    <td class="template">Óleos</td>
  </tr>
</table>

  • 1

    that’s what I needed. Thank you very much!

1

You can use jQuery to do the for only in the element you want

$(document).ready(function(){
  $("#table_marcas tr td.template").each(function(x,e){
     alert($(e).text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_marcas">
    <tr>
        <td>Nome</td>
        <td class="template">Óleos</td>
        <td class="template">Veículos</td>
        <td class="template">Óleos</td>
    </tr>
    <tr>
        <td>Nome</td>
        <td class="template2">Óleos2</td>
        <td class="template2">Veículos2</td>
        <td class="template2">Óleos2</td>
    </tr>
</table>

  • 3

    AP (author of question) tagged javascript only @Rafaellilo.

Browser other questions tagged

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