【问题标题】:Unable to Access HTMLElement无法访问 HTMLElement
【发布时间】:2020-10-06 10:03:00
【问题描述】:

我有一些代码使用 DOM Parser 将 HTML 字符串转换为 Document。然后根据类名遍历 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 Parser 转换的文档是,

Converted as Document

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

Converted differently

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

TypeError: 无法读取未定义的属性 'children'

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

我无法编写测试。

【问题讨论】:

  • 您正在调用helper.stringToHTML(htmlString),然后在该结果上调用helpers.stringToHTML(...)。好像搞错了?
  • 这实际上是一个错字,只是在尝试不同的东西。更新后问题依然存在。
  • 那么,DOMParser 在测试中的结果没有.getElementByClassName?那是对的吗?你得到什么样的错误,在哪一行?
  • @DimaParzhitsky 下面是错误,TypeError: Cannot read property 'children' of undefined at the line - htmlContent.getElementsByClassName('document-content')[0].children
  • 谢谢!您能否在原始问题中也添加此信息?

标签: javascript html dom jestjs domparser


【解决方案1】:

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

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

参考 - For loop for HTMLCollection elements

【讨论】:

  • 谢谢!。这适用于这种情况,但如果我想访问 item.innerText 之类的内容,它仍然会失败。
猜你喜欢
  • 2012-01-22
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 2014-01-29
  • 2022-10-14
  • 1970-01-01
相关资源
最近更新 更多