【问题标题】:Skip elements within a container when querying DOM查询 DOM 时跳过容器内的元素
【发布时间】:2018-04-12 07:02:06
【问题描述】:

当使用querySelectorAll 或任何 DOM 查询方法时,我想跳过给定子容器中的元素进行查询。

示例:

<div id="container-one">
    <div>
      <input type="text" name="first">
      <input type="text" name="second">

      <!-- skip below -->
      <div id="container-two">
        <input type="text" name="third">
        <input type="text" name="fourth">       
      </div>
    <div>
</div>

假设在上述情况下,如果您从#container-one 元素查询,您想跳过#container-two 中的元素。因此,#container-one 上的查询应该只返回 [first, second] 元素并跳过其他元素(第三、第四)。

感谢任何输入。

【问题讨论】:

    标签: dom jquery-selectors selectors-api


    【解决方案1】:

    试试这个:

    document.querySelectorAll('div.container-one')[0].querySelectorAll(':scope > input')
    

    更新(此时你不能使用 querySelectorAll):

    inputs = document.getElementsByTagName("input");
    input_two = document.getElementById('container-two').getElementsByTagName('input');
    
    var input_cont_two_name_array = [];
    for(j=0;j<input_two.length;j++){
        input_cont_two_name_array.push(input_two[j].name);
    }
    
    for(i=0;i<inputs.length;i++){
        input_name_id = inputs[i].name;
        if(input_cont_two_name_array.indexOf(input_name_id) == -1){
          //do your stuff
        }
    }
    

    【讨论】:

    • 输入元素可以在层次结构中的任何位置,而不仅仅是直接子元素。所以':scope &gt; input' 不会在这里工作。
    • 根据提供的信息,我为孩子们制作了它。如果你可以给我一个例子,我们可以看看可以做什么。
    • 即使它不是直接子元素,它也会为您提供输入元素...工作 jsfiddle jsfiddle.net/bjn5cafv 您可以检查控制台的日志
    • 我已经更新了我的问题中的 html,但您提供的解决方案不起作用。
    • 谢谢,但更新后的解决方案不是通用的。
    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2011-02-14
    • 2016-09-25
    • 2017-03-06
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多