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

removeChild-删除第一个或最后一个节点

  •  0
  • anjanesh  · 技术社区  · 8 年前

    我有一个jQuery one行程序,我正试图将其转换为普通的JavaScript。

    $('#nav ul li:' + (dir == -1 ? 'last' : 'first')).remove();
    

    这很管用。但是我需要5行来替换jQuery的一行吗?

    var li = document.querySelectorAll('#nav ul li');
    var first = li[0];
    var last = li[li.length- 1];
    theParent = document.querySelector("#nav ul");
    theParent.removeChild(dir == -1 ? last : first);
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   tao    8 年前

    用香草语写这句话最简单的方法是:

    var nodes = document.querySelectorAll("#nav ul li"),
        index = -1 == dir ? nodes.length-1 : 0;
    nodes[index].parentElement.removeChild(nodes[index]);
    

    …我想。(显然, nodes index 可以重命名为1个字母的变量名,可以删除空格,但这不是重点)。

    顺便说一下,正如q注释中指出的,您的版本没有正确删除 <li> 当有两个或更多 <ul> #nav

    测试:

    // comment/uncomment this to test:
    let dir = 1;
    
    var nodes = document.querySelectorAll("#nav ul li"),
        index = -1 == dir ? nodes.length-1 : 0;
    nodes[index].parentElement.removeChild(nodes[index]);
    <nav id="nav">
      <ul>
        <li>one</li>
        <li>two</li>
        <li>three</li>
      </ul>
      <ul>
        <li>fourth</li>
        <li>fifth</li>
        <li><ul>
          <li>sixth</li>
          <li>seventh</li>
        </ul></li>
      </ul>
    </nav>