JQuery / JavaScript: Choosing the first "layer" for children only

I try to select only the first "layer" of children of this type, but not elements nested in another qualification element. For instance. in:

<div id='top'> <div id="s1" class="special"> <div id="s2" class="special"></div> </div> <div> <div id="s3" class="special"></div> </div> </div> 

I would like to find # s1 and # s3, but not # s2, with something like $ ('# top'). find ('. special: not_nested'). Is this possible with jQuery? XPATH?

I was thinking about custom jQuery filters like expr [':']. not_nested, but I can’t understand how to take into account the top parent ($ ('# top') in this case, because there may be other special classes further in the parent chain #top.

[edit] I have to mention right now, I resort to a recursive call to $ .fn.children (), which I think is not very efficient.

[edit2] checked working code:

  var node = $('#top'), result = (node.find('.special').filter(function(){ return !($(this).parent().closest(".special", node).length); })); 

However, this does not work if "#top" has its own class. So maybe this:

 var node = $('#top'), result= node.find('.special').filter(function(){ var parent = $(this).parent().closest(".special", node); return !parent.length || parent.is(node); }); 
+4
source share
3 answers

Another option is to use .children() instead of .find() , but it will have the same result as the idrumgood solution.

 $('#top').children('.special') 

Edit: I realized that nesting is #s3 , this might work for this situation:

 $('#top').find('.special').filter(function(){ return $(this).closest('.special').length === 0; }).doSomething() 

Edit2: here ya go:

 $('#top').find('.special').filter(function(){ return !$(this).parent().closest(".special").closest("#top").length; }).doSomething; 
+3
source

$('#top > .special'); > -this is only direct deducts.

Besides the fact that your code has #s3 also built into an extra div, so I'm not sure if you really want to ask.

+3
source

If these are specifically those divs, you can try using a css selector with spaces, e.g.

 ".one .three" and ".one" 

for something like this

 <div class="one"> <div class="two"> <div class="three"> 
0
source

Source: https://habr.com/ru/post/1384785/


All Articles