Finding contents of a td from a class

0

I have the following lines inside 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 the class "template, and then check if there is any equal to" Oils ".

    
asked by anonymous 20.12.2016 / 19:15

2 answers

3

You can use getElementsByClassName to fetch all elements that have this class, then check the contents of it:

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>
    
20.12.2016 / 19:23
1

You can use jQuery to do only the elements 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><tableid="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>
    
20.12.2016 / 19:36