【问题标题】:Get all the elements id after a targeted element获取目标元素之后的所有元素id
【发布时间】:2018-12-25 19:44:10
【问题描述】:

那么如何获取目标元素之后的所有元素,例如,我想获取 id 调用 c 之后的所有元素,而不管 c 之后的元素数量如何

例如

d
e
f

我想在 id 元素调用输出中输出结果

这是我卡住的代码

/*
Get all the elements ids after the id call c and output those 
ids in the id call output 

For example 
document.querySelector('#output').innerHTML = ??;

How?
*/
#output{
  color: red;
}
<h1 id='a' class='letters'>A</h1>
<h1 id='b' class='letters'>B</h1>
<h1 id='c' class='letters'>C</h1>
<h1 id='d' class='letters'>D</h1>
<h1 id='e' class='letters'>E</h1>
<h1 id='f' class='letters'>F</h1>

<h1 id='output'></h1>

【问题讨论】:

    标签: javascript html dom selectors-api


    【解决方案1】:

    您可以使用document.querySelectorAll('#c ~ .letters'),它使用general sibling combinator

    document.querySelector('#output').innerHTML = Array.from(
      document.querySelectorAll('#c ~ .letters')
    ).map(element => element.textContent).join(' ');
    #output{
      color: red;
    }
    <h1 id='a' class='letters'>A</h1>
    <h1 id='b' class='letters'>B</h1>
    <h1 id='c' class='letters'>C</h1>
    <h1 id='d' class='letters'>D</h1>
    <h1 id='e' class='letters'>E</h1>
    <h1 id='f' class='letters'>F</h1>
    
    <h1 id='output'></h1>

    【讨论】:

      【解决方案2】:

      这里没有冒犯其他示例,但我注意到这里的一些代码示例在某些浏览器上会存在一些兼容性问题,例如

      IE 11 所以这适用于我测试过的所有主要浏览器。以防万一你试图让它在 IE 11 上工作,所以这是我的例子......

      var afterC = [].slice.call(document.querySelectorAll('#c ~ *.letters')).map(function(elem){ return elem.getAttribute('id');});
      
      document.querySelector('#output').innerHTML = afterC;
      #output{
        color: red;
      }
      <h1 id='a' class='letters'>A</h1>
      <h1 id='b' class='letters'>B</h1>
      <h1 id='c' class='letters'>C</h1>
      <h1 id='d' class='letters'>D</h1>
      <h1 id='e' class='letters'>E</h1>
      <h1 id='f' class='letters'>F</h1>
      
      <h1 id='output'></h1>

      【讨论】:

      • 感谢大家对这篇文章的回复,但我觉得 Thomas Wayne 的方法很适合我的风格,所以谢谢 Thomas Wayne 这解决了我的问题。
      【解决方案3】:

      获取 c 的位置,然后取下面的所有 h1s':

       const c = document.querySelector("#c");
       const h1s = [...document.querySelectorAll("h1")];
       const position = h1s.indexOf(c);
      
       const result = h1s.filter((_, i) => i > position);
      
        for(const entry of result)
          output.appendChild(entry.cloneNode(true));
      

      【讨论】:

        【解决方案4】:

        一种可能的方式:

        // using a named function, passing in a CSS selector:
        let getAllAfter = function(selector) {
        
          // here we return the result of document.querySelectorAll(),
          // after using Array.from() to convert the Array-like NodeList
          // to an Array:
          return Array.from(
            document.querySelectorAll(
              // using the passed-in selector and concatenating that
              // with the general sibling combinator ('~') and, in this
              // case using '.letters' to restrict the selector to elements
              // containing that class:
              selector + '~ .letters')
          );
        }
        
        // setting the textContent of the element with the id of 'output'
        // to be equal to the Array of elements - having mapped
        // their textContent using Array.prototype.map(), and joining
        // the resulting Array using Array.prototype.join():
        document.getElementById('output').textContent = getAllAfter('#c').map(el => el.textContent).join(', ');
        #output {
          color: red;
        }
        <h1 id='a' class='letters'>A</h1>
        <h1 id='b' class='letters'>B</h1>
        <h1 id='c' class='letters'>C</h1>
        <h1 id='d' class='letters'>D</h1>
        <h1 id='e' class='letters'>E</h1>
        <h1 id='f' class='letters'>F</h1>
        
        <h1 id='output'></h1>

        当然,这是使用硬编码的选择器,它在不同的上下文中并不是特别有用,因此要修改上述函数以接受第二个选择器,将选定的后续兄弟限制为一个选择器:

        // using a named function, passing in a CSS selector:
        let getAllAfter = function(targetSelector, siblingSelector) {
        
          // here we return the result of document.querySelectorAll(),
          // after using Array.from() to convert the Array-like NodeList
          // to an Array:
          return Array.from(
            document.querySelectorAll(
              // using the passed-in selector and concatenating that
              // with the general sibling combinator ('~') and, in this
              // case using '.letters' to restrict the selector to elements
              // containing that class:
              targetSelector + ' ~ ' + siblingSelector)
          );
        }
        
        // setting the textContent of the element with the id of 'output'
        // to be equal to the Array of elements - having mapped
        // their textContent using Array.prototype.map(), and joining
        // the resulting Array using Array.prototype.join():
        document.getElementById('output').textContent = getAllAfter('#c', '.letters').map(el => el.textContent).join(', ');
        #output {
          color: red;
        }
        <h1 id='a' class='letters'>A</h1>
        <h1 id='b' class='letters'>B</h1>
        <h1 id='c' class='letters'>C</h1>
        <h1 id='d' class='letters'>D</h1>
        <h1 id='e' class='letters'>E</h1>
        <h1 id='f' class='letters'>F</h1>
        
        <h1 id='output'></h1>

        当然,在兼容的浏览器中,我们可以避免串联字符串,只需使用模板文字将提供的字符串转换为选择器:

        // using a named function, passing in a CSS selector:
        let getAllAfter = function(targetSelector, siblingSelector) {
        
          // here we return the result of document.querySelectorAll(),
          // after using Array.from() to convert the Array-like NodeList
          // to an Array:
          return Array.from(
            document.querySelectorAll(
              // using the passed-in selector and concatenating that
              // with the general sibling combinator ('~') and, in this
              // case using '.letters' to restrict the selector to elements
              // containing that class:
              `${targetSelector} ~ ${siblingSelector}`)
          );
        }
        
        // setting the textContent of the element with the id of 'output'
        // to be equal to the Array of elements - having mapped
        // their textContent using Array.prototype.map(), and joining
        // the resulting Array using Array.prototype.join():
        document.getElementById('output').textContent = getAllAfter('#c', '.letters').map(el => el.textContent).join(', ');
        #output {
          color: red;
        }
        <h1 id='a' class='letters'>A</h1>
        <h1 id='b' class='letters'>B</h1>
        <h1 id='c' class='letters'>C</h1>
        <h1 id='d' class='letters'>D</h1>
        <h1 id='e' class='letters'>E</h1>
        <h1 id='f' class='letters'>F</h1>
        
        <h1 id='output'></h1>

        参考资料:

        【讨论】:

          猜你喜欢
          • 2020-05-10
          • 2021-07-02
          • 2019-07-10
          • 1970-01-01
          • 2021-11-04
          • 1970-01-01
          • 2022-01-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多