How can I use jQuery find() with a depth limit?

Fabio K picture Fabio K · Apr 8, 2013 · Viewed 13.8k times · Source

I need to use jquery's "find" selector to get all divs having the class "field_container". The problem is that I can't go too deep in the DOM tree.

Here is my simplified HTML structure:

<div id='tab_0'>

 <div id='form_content'>

  <div class='field_container'>
   <span>Div 1</span>
   <div class='field_container'>
   <span>Div 1.1</span>
   </div>
  </div>

  <div class='field_container'>
   <span>Div 2</span>
  </div>

  <div class='field_container'>
   <span>Div 3</span>
  </div>

 </div> <!-- Closing form_content div//-->

</div> <!-- Closing tab_0 div//-->

I have a initial reference to the "tab_0" div. Starting from it, I need to obtain all "field_container" divs, excluding child "field_containers".

I have tried this:

$('#tab_0').children('.field_container') -> doesnt work, because the "field_container" divs arent direct children.

$('#tab_0').find('.field_container') -> doesnt work, because "Div 1.1" is also returned. I only need the first-level ones (Div1, Div2, Div3).

I can't change my initial reference, it has to be "tab_0".

Answer

Christoph picture Christoph · Apr 8, 2013

There are several possibilities to solve this.

A rather quick one is:

$('#tab_0').children('#form_content').children('.field_container')

due to it's restriction of only traversing one level into the DOM tree each. I'm not entirely sure but this should be quicker (but in every case simpler) than a find() with a complex selector.