jQuery/JavaScript: selecting first “layer” of children only

北城余情 提交于 2019-12-10 09:08:06

问题


I'm trying to select only the first "layer" of children elements of a given type, but not elements nested inside another qualifying element. E.g. 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'd like to find #s1 and #s3, but not #s2, with something like $('#top').find('.special:not_nested'). Is it possible with jQuery? XPATH?

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

[edit] I should mention right now I'm resorting to a recursive call to $.fn.children() which I think is not very efficient.

[edit2] tested working code:

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

However, this doesn't work if "#top" has .special class itself. 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);
});

回答1:


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

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

Edit: i just realized the nesting of #s3, this may work for that 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;



回答2:


$('#top > .special'); the > is only direct decedents.

Except your code has #s3 also nested inside a secondary div, so I'm not sure if you're really wanting what you asked.




回答3:


If it's specifically those divs, you might want to try using css selectors with spaces, like

".one .three" and ".one" 

for something like this

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


来源:https://stackoverflow.com/questions/8391925/jquery-javascript-selecting-first-layer-of-children-only

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