Reputation: 89
I'm trying to select elements with jquery ionly on a specific level. They have to be directly sub of #main->table
and contain the class x
.
I'm trying something like that $('#main>table .column');
But with this i also get the second level div with the class "x" (total 3). I need just the two elements which are marked in the example with "wanted". I'm unfortunately not able to make any changes on the code...
Maybe there is something possible like $('#main>table .column:first-child');
? Somehow that returns me 3elements as well. Best would be a possibility to consider only a specific number of levels
<div id=main>
<div class=x> <!-- not wanted -->
<table>
<tr>
<td>
<div class=x> <!-- wanted -->
<table>
<tr>
<td>
<div class=x></div> <!-- not wanted -->
</td>
</tr>
</table>
</div>
</td>
<td>
<div class=x></div> <!-- wanted -->
</td>
</tr>
</table>
</div>
</div>
Thanks in advance for your help!
Upvotes: 1
Views: 115
Reputation: 23664
If the class 'x' indicates a markup for level you could fileter the results based on parents length.
$('.x').filter(function(i,e) {
return $(e).parents('.x').length === 1;
})
This way you could easily reuse the code:
$.fn.filterAt = function(level, selector) {
var ps = selector || this.selector;
return this.filter(function(i,e) {
return $(e).parents(ps).length === level;
});
};
$('.x').filterAt(1);
Tested using jQuery 1.7.2
Upvotes: 0