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

萝らか妹 提交于 2019-12-10 03:02:14

问题


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


回答1:


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.




回答2:


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(){...});



回答3:


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)');


来源:https://stackoverflow.com/questions/15880037/how-can-i-use-jquery-find-with-a-depth-limit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!