Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

find

depth

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".

like image 871
Fabio K Avatar asked Apr 08 '13 13:04

Fabio K


3 Answers

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.

like image 108
Christoph Avatar answered Nov 07 '22 21:11

Christoph


For more complexe filtering than your current example, you should use filter. Here, this do the trick:

$('#tab_0').find('.field_container').filter(function(){return $(this).parent()[0].id === "form_content"}).each(function(){...});
like image 3
A. Wolff Avatar answered Nov 07 '22 22:11

A. Wolff


Is the nesting consistent? If so you can do this:

$('#tab_0').find('#form_content > .field_container');

If not you can do this (although it's less efficient):

$('#tab_0').find('.field_container:not(.field_container .field_container)');
like image 1
jmar777 Avatar answered Nov 07 '22 21:11

jmar777