mardi 10 avril 2018

unknown if statement in javascript

what does if(td) condition does here? This code is written to search a row in a table. var input is the search box, var table is the table.

function myFunction() {
    // this function filters the table using search box
    var input, filter, table, tr, td, i;

    input = document.getElementById("myInput"); // the search box
    filter = input.value.toUpperCase();
    table = document.getElementById("myTable"); // the table
    tr = table.getElementsByTagName("tr");      // the row of table

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {  // why do we need this condition here?
            if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }       
    }
}

Aucun commentaire:

Enregistrer un commentaire