Problems with JavaScript on WordPress

I'm trying to develope an event on JavaScript in a WordPress page that after clicking a href can display a colum but I have this error:

Uncaught TypeError: Cannot read property 'style' of undefined
at show_hide_column ((index):212)
at HTMLAnchorElement.onclick

The code which I have for the script is:

function show_hide_column(col_no, do_show) {
    alert(col_no);
    var stl;
    if (do_show)
        stl = 'block'
    else
        stl = 'none';

    var tbl = document.getElementById('id_of_table');
    var rows = tbl.getElementsByTagName('tr');
    for (var row = 0; row < rows.length; row++) {
        var cels = rows[row].getElementsByTagName('td')
        cels[2].style.display = stl;
    }
}

Html:

<table id="id_of_table" width="966">
  <tbody>
   <tr>
    <td colspan="3" width="966"><strong>POLITICA DE PRIVACIDAD </strong></td>
</tr>
<tr>
 <td width="187"><strong>       </strong></td>
 <td width="227"><strong>1ª CAPA - Información básica</strong></td>
 <td width="553"><strong>2ª CAPA- Información adicional</strong></td>
</tr>
<tr>
 <td width="187"><strong>RESPONSABLE</strong></td>
 <td width="227"><a href="#" onClick='javascript:show_hide_column(2, false);'>RED S.L.</a></td>
  <td width="553">

    La entidad encargada de atender todas las cuestiones relativas al tratamiento de los datos de carácter personal  en relación al uso de la APLICACIÓN será  RED S.L. (en adelante “LA EMPRESA”). En este sentido, se indican los siguientes datos de contacto:
  </td>
   </tr>
 </table>

What happen with this error?. Thanks so much

1 answer

  • answered 2018-01-14 18:18 LetsGoRangers

    The error coming from the first tr since it only have one td. You can separate the top tr and the other with thead and tbody, then only loop the tbody.

    Another tip, you can change this:

    var stl;
    if (do_show)
        stl = 'block'
    else
        stl = 'none';
    

    To this:

    var stl = (do_show) ? 'block' : 'none';