javascriptjqueryjquery-selectors

Querying a table in Jquery


I have encountered this code

$("#search").keyup(function(){
  var val = $.trim(this.value).toLowerCase();
   $("table > tbody > tr:gt(0) ").hide();

   if(val.length){
     $("table > tbody > tr:gt(0) > td").filter(function(){
       return this.innerHTML.toLowerCase().indexOf(val) >=0;
     }).parent().show();
   } else $("table > tbody > tr:gt(0)").show();
});

For Querying a a table in jQuery. here's the HTML markup

<p>
  <input id = "search" type = "text">
</p>
<table id ="accounts">
  <tr>
    <th>Username</th>
    <th>Password</th>
  </tr>         
  <tr>
    <td>Metasm</td>
    <td>password1992</td>
  </tr>
  <tr>
    <td>superadmin</td>
    <td>adminpassword</td>
  </tr>         
  <tr>
    td>skyrocketeer</td>
    <td>thejetsons</td>
  </tr>
</table>

Basically it works. but the I am very confused with regards to the jQuery code.

My Question: in this part of code

$("table > tbody > tr:gt(0) > td").filter(function(){
  return this.innerHTML.toLowerCase().indexOf(val) >=0;
}).parent().show();

What does this part specifically do? and what does it return?


Solution

  • So what this is saying (remembering that we are iterating over all the elements we found from our first selector) is that we are looking for an occurance of the string val within the innerHTML of the element. The innerHTML is also being passed through the toLowerCase() function, who's name suggests is function - converts all characters to their lowercase form.

    Phew...Now after all this we are left with a certain list of elements. Elements that met all of our specifications above. For each of these elements, the code will locate their parent (remember we are talking about <td> elements, so their parents should be <tr>) with the .parent() function and display them on screen with the .show() function.


    For the first selector - $("table > tbody > tr:gt(0) > td"), I find sometimes its easier to read it backwards (in your mind) to understand the hierarchy...

    Return the -

    1. I'm looking for <td> elements,
    2. that are inside <tr> elements (but not the first one),
    3. that are inside a <tbody> element
    4. that all reside within a <table> element.

    Now for some sample input and output: