【问题标题】:How do I Convert a HTML Collection into an array, without emptying it? #2如何在不清空 HTML 集合的情况下将其转换为数组? #2
【发布时间】:2021-03-01 19:50:50
【问题描述】:

我正在尝试将“li”的 HTML 集合转换为数组,但数组中的结果被清空。

我阅读了这个问题并应用了它,但它不起作用。How do I convert a HTMLCollection into an array, without emptying it?

<body>
  <ul id="base"></ul>
  <script>
   const json = [{
     "id" : "1", 
     "date" : "2013/05/05",
    },{
     "id" : "2", 
     "date" : "2019/05/05",
    }];

    for (item of json) {
      const list = document.createElement('li');
      list.textContent = `${item.date}`;
      base.appendChild(list)
    }
///the code above works fine.

    const base = document.getElementById("base");
    const myNodeList = base.getElementsByTagName("li");
    console.log(myNodeList);
    // gives HTMLCollection
    const myArray = Array.from(myNodeList)
    // returns empty array
  </script>
</body>

结果

我在控制台上测试了相同的代码,它运行良好,如下所示。

【问题讨论】:

  • 如果您只想使用数组原型方法,您可以执行以下操作:Array.prototype.arrayMethod.call(htmlCollection, () =&gt; {});arrayMethod 可以是您可以在数组上调用的任何方法,例如 fllter、forEach、map 等。 HTML 集合是 document.getElementsByTagName 返回的 NodeList。如果您要处理文档中的大量节点,则性能会好得多。

标签: javascript dom


【解决方案1】:

在初始化之前使用base 之前,代码无法运行。在使用它之前放置初始化使其工作。

这里我修改了一下:https://jsfiddle.net/tk78z5gq/

【讨论】:

    【解决方案2】:

    非常感谢你们! 问题是异步的。 我早该说过,我使用异步函数从 NeDB 获取数据。 该数组为空,因为 DOM 在异步函数获取数据之前执行。 下面的完整代码是固定的。我不确定这是不是最好的方法,但至少它有效。

        let dataM = null;
    
        async function getHTMLData() {
          const response = await fetch('/api');
          const data = await response.json();
          dataM = data;
          const base = document.getElementById("base");
    
          for (item of data) {
            const root = document.createElement('li');
            root.className = "col-md-auto";
            root.title = `${item.date}`;
            const border = document.createElement('div');
            border.className = "row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative";
            root.appendChild(border);
            const flex = document.createElement('div');
            flex.className = "col p-4 d-flex flex-column position-static";
            border.appendChild(flex);
            const country = document.createElement('strong');
            country.className = "d-inline-block mb-2 text-primary";
            const title = document.createElement('h3');
            title.className = "mb-0";
            const date = document.createElement('div');
            date.className = "mb-1 text-muted";
            date.id = "date";
            const fieldItem = document.createElement('p');
            fieldItem.className = "mb-auto";
            const imageRoot = document.createElement('figure');
            imageRoot.className = "image mb-2";
            const link = document.createElement('a');
            link.className = "p-4";
            const linkText = document.createTextNode("Source");
    
            country.textContent = `${item.country}`;
            title.textContent = `${item.title}`;
            date.textContent = `${item.date}`;
            fieldItem.textContent = `${(item.fieldItem)}`;
    
            for (var i = 0; i < item.imageSrc.length; i++) {
              const image = document.createElement('img');
    
              image.src = item.imageSrc[i];
              image.alt = 'seized items'
              image.className = "w-5 h-5";
              // image.crossOrigin ="use-credentials";
              imageRoot.appendChild(image);
            }
            const imageText = document.createElement('text');
            imageText.innerHTML = `<br>${item.imageText}`;
            imageRoot.appendChild(imageText);
            link.appendChild(linkText);
            link.title = "Source";
            link.href = item.URL;
            link.className = "";
    
            flex.append(country, title, date, fieldItem, imageRoot, link);
            base.appendChild(root);
          }
        }
    
        sortDate();
        async function sortDate() {
          const gethtml = await getHTMLData();
          const base = await document.getElementById("base");
          const myNodeList = await base.getElementsByTagName("li");
          const myArray = Array.from(myNodeList);
          myArray.sort(function (a, b) {
            return new Date(a.title) > new Date(b.title)? -1
                 : new Date(a.title) < new Date(b.title)? 1
                 : 0;
            })
          for (i = 0; i < myArray.length; i++) {
            base.appendChild(base.removeChild(myArray[i]))}
        } 
    

    index.js

    app.get('/api', (request, response) => {
      database.find({}).exec(function(err, data){
        if (err) {
          response.end();
          return;
        }
        response.json(data);
      })
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-17
      • 1970-01-01
      • 2015-11-10
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多