代码之家  ›  专栏  ›  技术社区  ›  Soviut

这是查询元素及其子元素的最佳方法吗?

  •  0
  • Soviut  · 技术社区  · 14 年前

    我正在尝试查询一个元素 它的子对象将查找以特定字符串开头的ID。

    var foundIDs = containerElement.find('[id^=something]').andSelf().filter('id^=something');
    

    find() 方法只能搜索后代所以我想我应该试试 andSelf() . 然而, 和赛尔夫() 不接受选择器。这意味着不管容器元素是否与find查询匹配,都会包含容器元素,然后我必须执行第二次查询 filter() 如果容器元素不匹配,则删除它。

    我试图把 这个 查找()

    containerElement.andSelf().find('[id^=something]');
    

    有没有更好的方法来实现我的目标?

    4 回复  |  直到 14 年前
        1
  •  1
  •   Philippe Leybaert    14 年前

    就在我头上(没有测试):

    var foundIDs = containerElement
                         .filter('id^=something')
                         .add(containerElement.find('id^=something'));
    

        2
  •  1
  •   James    14 年前
    containerElement.find('*').andSelf().filter('[id^=something]');
    
        3
  •  1
  •   user113716    14 年前

    我知道你已经接受了一个答案,但我还是会把这个答案扔出去。

    var foundIDs = containerElement.wrap('<div>')             // Wrap
                                   .parent()                  // Traverse up
                                   .find('[id^=something]');  // Perform find
    
    containerElement.unwrap();  // DOM is untouched
    

    因为你正在解开包裹 containerElement 在函数完成之前,DOM保持不变(以防您感到奇怪)。

    我跟他核实过了 livequery div .

    如果您记录foundIDs的ID(或其他),您将看到顶层是您的containerElement(假设它与 .find() 标准。

    console.log( foundIDs.attr('id') );  // Log the ID of the root element.
    

    编辑:

    集装箱

    我只在Mac上进行了Safari测试。

    公认的答案大约快了7倍。

    麻烦来了。如果 集装箱 不匹配。我不知道这是为什么。

        4
  •  1
  •   user113716    14 年前

        // Do a typical find.
    var found = containerElement.find('[class^=something]');
    
        // Test the containerElement directly,
        //    and push it into the 'found' object if it matches.
    if( containerElement.is('[class^=something]') ) found.push(containerElement);