如何选择从“X”类的节点A终止路径的所有节点S的集合,其中只有根节点和终端节点属于“X”类?

时间:2014-05-20 22:30:09

标签: jquery jquery-selectors

基本上我正在寻找一种选择子“my-class”节点的方法,即使它们不是直接的子节点,并且在给定任何“my-class”元素的情况下不选择任何孙子“my-class”节点。 例如,给定“a”它将返回“b”,“g”。给定“b”它将返回“c”,“f”,给定“c”将返回“d”,“e”和“d”将不返回任何内容。如果没有遍历DOM,我似乎无法找到一种方法。

<div class="my-class" id="a">
  <div>
    <div class = "my-class" id="b">
      <div class = "my-class" id="c">
        <div class = "my-class" id="d">
        </div>
        <div class = "my-class" id="e">
        </div>
      </div>
      <div class = "my-class" id="f">
      </div>
    </div>
    <div>
      <div class = "my-class" id="g">
        <div>
          <div>
            <div class="my-class" id="h">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

我现在正在做的只是遍历DOM。如果它的“我的类”执行我的操作,并且它不继续遍历树的那一部分。

function traverse(element) {
  $(element).children(".my-class").trigger("my-event");
  var children = $(element).children(":not(.my-class)");
  for (var i = 0; i < children.length; i++) {
    traverse(children[i]);
  }
}

2 个答案:

答案 0 :(得分:1)

尝试:

var $children = $('.my-class').children();

.children()将为您的选择器提供直接后代。

  

.children()方法与.find()的不同之处在于.children()只沿DOM树向下移动一个级别,而.find()可以遍历多个级别以选择后代元素(孙子等)同样。

答案 1 :(得分:0)

从指定的$root递归检查DOM树中的每个路径。 var type是你可以放入jQuery in()方法的任何东西,包括选择器。

$.extend({findKids: function($el, type)
    {

        //define our recursive function
        var findPaths = function($el, $root, type)
        {
            //terminating step:
            //if the node is not the root, 
            //and is a type of "type", add 
            //it to the result set and return
            if ($el.is(type) && !$el.is($root))
            {
                $foundNodes = $foundNodes.add($el);
                return 1;
            }
            else
            {
                //recursive step:
                //look at the first generation of the element's children
                $el.children().each(function() {
                    //check in child to see if its of "type" or not
                    findPaths($(this), $root, type);
                });
            }
        }
        //store everything we find:
        $foundNodes = $();

        //call it once
        findPaths($el, $el, type);
        //found nodes will be in foundNodes
        return $foundNodes;
    }});

<强>结果

console.log($.findKids($('#a'), '.my-class')); //#b, #g
console.log($.findKids($('#b'), '.my-class')); //#c, #f
console.log($.findKids($('#c'), '.my-class')); //#d, #e
console.log($.findKids($('#d'), '.my-class')); //empty