2

(General question was indeed already asked, but the answer given here gives a nice way to solve the problem posed here, instead of the other question's 'behind the scenes' explanation...)

I'm trying to highlight all the cells in a table (with embedded tables) that contains an input field.

Sample code: jsFiddle

I can do it with $('#rec td:has(>input)') but I would prefer to use the .has() method as the doc for the :has() selector mentions performance issues - my table can become quite big with several embedded tables and I - still - have to support IE6...

However, $('#rec td').has('>input') does not work (it includes cells which does not actually have an <input> as a direct child), seemingly ignoring the > child selector...

Is there a way to get the same result with the .has() method as with the :has() selector?

Goozak
  • 508
  • 1
  • 5
  • 21

3 Answers3

2

I believe it will be more efficient to find all input's first, then their parent td's:

$('#rec input').closest('td').css('background-color', 'blue');

This way it shall not be needed to inspect every table cell and its children.

FIDDLE

esycat
  • 1,324
  • 11
  • 10
  • Ah... Reverse logic! I keep forgetting that it's sometimes best to attack the problem from the other side. :-) Thanks – Goozak Jul 06 '13 at 15:44
  • Ended up using `$('#rec input').parent('td')` to limit the element returned to the direct parent of the `input` (`closest` will keep going through ancestors until it find a `td`). – Goozak Jul 08 '13 at 13:36
0

Try removing > from the .has()

Jeff
  • 12,085
  • 12
  • 82
  • 152
  • .has() "Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element." It does not return bool. .filter() "Reduce the set of matched elements to those that match the selector or pass the function’s test." It does not do what I want here. – Goozak Jul 06 '13 at 15:36
  • Following change in answer: Removing the `>` from the `.has()` actually works as I would expect it - it includes TDs which doesn't have an input as a direct child, hence the need for the `>`. That's why I said that `.has()` seems to ignore the `>`. – Goozak Jul 06 '13 at 15:43
  • Yes, sorry, I edited my answer. – Jeff Jul 06 '13 at 15:43
0
$('#rec td').has('input').addClass('highlight')

or

$.each($('#rec td').has('input'), function(){
    $(this).addClass('highlight');
});
Adrian Trainor
  • 267
  • 1
  • 9
  • `.has()` will check all descendants of an element, I want to only check direct children of the element. That's why I tried adding the `>` which seems to be ignored. – Goozak Jul 06 '13 at 15:51