Katie Katie - 14 days ago 5
jQuery Question

jQuery - select an element which contain n number of duplicate child elements

This is the HTML I have to work with. The

spacer
classes basically indent the text.

<table>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
HEADING 1
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
<span class="spacer"></span>
SUBHEADING 1
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
<span class="spacer"></span>
SUBHEADING 2
</td>
</tr>
<tr>
<td>
<span class="spacer"></span>
<span class="spacer"></span>
HEADING 2
</td>
</tr>
</table>


How should I form my jQuery selectors so that I'm able to grab the rows for Headings? and for Subheadings?

I've tried
$(tr).has('td.spacer')
but this doesn't really help since they all use it and have multiples (2 for "headings" and 3 for "subheadings")

Answer

You could filter

var f = function(n) {
    return function() {
        return $(this).find('.spacer').length === n;
    }
}

var headings   = $('td').filter( f(2) );
var subheading = $('td').filter( f(3) ); 
// ..etc

var f = function(n) {return function() {return $(this).find('.spacer').length === n}};

$('td').filter( f(2) ).css('color','red');
$('td').filter( f(3) ).css('color','blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
 <tr>
  <td>
   <span class="spacer"></span>
   <span class="spacer"></span>
   HEADING 1
  </td>
 </tr>
 <tr>
  <td>
   <span class="spacer"></span>
   <span class="spacer"></span>
   <span class="spacer"></span>
   SUBHEADING 1
  </td>
 </tr>
 <tr>
  <td>
   <span class="spacer"></span>
   <span class="spacer"></span>
   <span class="spacer"></span>
   SUBHEADING 2
  </td>
 </tr>
 <tr>
  <td>
   <span class="spacer"></span>
   <span class="spacer"></span>
   HEADING 2
  </td>
 </tr>
</table>