Jonathan Wood
Jonathan Wood

Reputation: 67195

Combining Selectors

Given the following HTML:

<table>
  <tr id="row1">
    <td class="CommandLinks">
      <input type="checkbox" class="CommandLinks" />
    </td>
    <td class="Class2">
      <input type="text" value="1">
    </td>
    <td class="Class3">
      <input type="text" value="1">
    </td>
    <td class="Class4">
      <input type="text" value="1">
    </td>
    <td class="Class5">
      <input type="text" value="1">
    </td>
  </tr>
  <tr id="row2">
    ...
  </tr>
  ...
</table>

I can obtain the first checkbox using:

var row = $('tr#row1');
var checkbox = row.find('input[data-trackingid]');

However, it occurs to me that there is a little bit of extra overhead as jQuery has to scan every cell in the row. I was thinking about something like row.find('tr[class=CommandLinks] > input[data-trackingid]') but I see that doesn't work.

How could I modify the query above so that it only looks in $('tr[class=CommandLinks]')?

Note: I realize there are other ways to find this checkbox, but in my actual application I want to search by the attribute, as shown above.

Upvotes: 0

Views: 184

Answers (2)

Mathew Thompson
Mathew Thompson

Reputation: 56429

First, you don't need to do tr#row1. The ID selector will only ever look for one.

Just use the following, you shouldn't have any performance concerns:

var checkbox = $('#row1 .CommandLinks input[data-trackingid=foo]');

As shown below, it's slightly faster, but not by a great deal!

1

jsPerf: http://jsperf.com/jquerychildrenperf

Upvotes: 1

c-smile
c-smile

Reputation: 27460

This should work:

var row = $('tr#row1');
var checkbox = row.find('td.CommandLinks > input[data-trackingid]');

If data-trackingid is set on that element.

Or this:

var row = $('tr#row1');
var checkbox = row.find('td.CommandLinks').find('> input[data-trackingid]');

which is equivalent in jQuery.

Upvotes: 1

Related Questions