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".
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.
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(){...});
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)');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With