代码之家  ›  专栏  ›  技术社区  ›  Daniel Viglione

在ES6中为HTMLCollection DOM traversel使用数组类方法

  •  0
  • Daniel Viglione  · 技术社区  · 7 年前

    我试图避免使用jQuery进行DOM操作。我更喜欢使用ES6功能。ES6有一个健壮的数组类,因此我正在考虑将HTMLCollection对象转换为数组,然后使用数组类解析它们:

    actual = [ '10/12/2018', 'Affidavit', 'Party', 7 ];
    collection = Array.prototype.slice.call( document.querySelector('#tblEvents').rows )
    target_row = collection.find(function(row){
      predicate = row.cells[0].innerText.trim() == actual[0] && row.cells[1].innerText.trim() == actual[1] && row.cells[4].innerText.trim() == actual[3];
      if(predicate){
        if(actual[2] !== null && actual[2] !== ''){
          return actual[2] == row.cells[2].innerText.trim();
        } else {
          return true;
        } 
      }
    
      return false;
    })
    

    我在这里使用的es6方法是 . 但是HTMLCollection没有这样的方法。

    这是ES6的合适解决方案还是HTMLCollection类提供了类似的解决方案?

    3 回复  |  直到 7 年前
        1
  •  2
  •   loganfsmyth    7 年前

    Array.from :

    const collection = Array.from(document.querySelector('#tblEvents').rows);
    
        2
  •  0
  •   Stoil Ivanov    7 年前

    ES6没有为DOM操作添加任何新内容。。。至于jQuery,它只是一个使事情变得更简单的库(还规范了浏览器之间的不同行为)。

    DOM操作-搜索、添加、删除和编辑页面中的元素。

    可以使用以下方法之一选择DOM元素

    1. document.querySelector();
    2. doucment.querySelectorAll();
    3. document.getElementById();
    4. document.getElementsByName();

    编辑:

    let element = document.querySelector();
    element.innerHTML = "Hello World";
    element.setAttribute('data-custom', 123);
    

    删除:

    document.removeChild(childNode);        
    

    您可以在以下网址阅读更多内容:

    The HTML DOM Element Object

    Document Object Properties and Methods

        3
  •  0
  •   Felix B.    7 年前

    spread syntax :

    const collection = [...document.querySelector('#tblEvents').rows];
    

    关于将HTMLCollection协调到数组的最有效方法,有一个问题,讨论了各种方法: Most efficient way to convert an HTMLCollection to an Array