首页 > 解决方案 > 无法访问 HTMLElement

问题描述

我有一些代码,我使用 DOM Parser 将 HTML 字符串转换为 Document。然后根据类名遍历 DOM 找到一个元素。

助手.js

export function stringToHTML(htmlString) {
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlString, 'text/html');
  return doc.body; 
}

export function getTextBoxInfo(htmlContent) {
  const textBox = {
    element: null,
    index: null
  };

  htmlContent.getElementsByClassName('document-content')[0].children.forEach((ele, index) => {
    if (ele.getAttribute('class').includes('freetext')) {
      textBox.element = freeTextElement;
      textBox.index = index;
    }
  });

  return textBox;
}

helper.test.js

describe('The getTextBoxInfo function', () => {
    it('returns an object with text box element and its position', () => {
        const htmlString = `<div class="document-content">
            <div class="content" id="bfb53c88"> Heading </div>
            <div class="freetext" contenteditable="true"> Content </div>
        </div>`;
        const htmlContent = helper.stringToHTML(htmlString);

        const textBox = helper.getTextBoxInfo(htmlContent);
        expect(true).toBe(true);
    });
});

它适用于源代码。由 DOM Parser 转换的文档是,

转换为文档

但是在单元测试(JEST)期间输出不同,

转换方式不同

结果规范失败并出现以下错误,

TypeError:无法读取未定义的属性“孩子”

在线 - htmlContent.getElementsByClassName('document-content')[0].children

而且我无法编写测试。

标签: javascripthtmldomjestjsdomparser

解决方案


而不是 forEach,使用普通的 for-loop 或 for-of 循​​环,因为您将孩子作为 HTMLCollection

const children = htmlContent.getElementsByClassName('document-content')[0].children;
    for (let item of children) {
        console.log(item);
    }

参考 - HTMLCollection 元素的 For 循环


推荐阅读