Devraj Gadhavi Devraj Gadhavi - 7 months ago 43
HTML Question

jQuery: select tr having all td matching the filter criteria dynamically

Title might be a bit confusing, but this is the best I could come up with.

I need to find all

tr
elements which contains
td
elements matching the filter criteria provided.

Here is my sample,

<tr class="row" id="1">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="lamp">Lamp<td>
</tr>
<tr class="row" id="2">
<td class="philips">PHILIPS</td>
<td class="h5">H5</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="3">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="4">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="5">
<td class="osram">OSRAM</td>
<td class="hb3">HB3</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="6">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="lamp">Lamp<td>
</tr>


If I pass
filter[0]
as 'phillips', the result return
tr
with id


  • 1

  • 2 and

  • 4



Then if I pass second filter;
filter[1]
as 'h4', the result should be filtered down to


  • 1 and

  • 4



I have tried this question.

Which has this answer.

$('tr')
.has('td:nth-child(1):contains("Audi")')
.has('td:nth-child(2):contains("red")')
.doSomeThing();


But, I want my filters to be applied dynamically. How would I be able to insert a 3rd
has
function?

I don't want to go the
if-else
or
switch-case
way, if this is possible with out them.

Red Red
Answer

You can try this.

<script type="text/javascript">
    $(document).ready(function () {
        var result =  filter([".philips", ".h4"]);
        alert(result);
        var result_2 = filter([".philips"]);
        alert(result_2);
    });

    function filter(params) {
        var select = "tr";

        for (var i = 0; i < params.length; i++) {
            select += ":has(" + params[i] + ")";
        }

        return $(select).map(
              function () { 
                  return $(this).attr('id');
              }
        ).get();
    }
</script>