无法访问 HTMLElement

Unable to Access HTMLElement

我有一些代码,我使用 DOM 解析器将 HTML 字符串转换为文档。然后根据class名称遍历DOM找到一个元素

helper.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 解析器转换的文档是,

Converted as Document

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

Converted differently

因此规范失败并出现以下错误,

TypeError: Cannot read property 'children' of undefined

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

而且我无法编写测试。

而不是 forEach,使用正常的 for-loop 或 for-of 循环,因为你得到 children 作为 HTMLCollection

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

参考 - For loop for HTMLCollection elements