javascript - 无法访问 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
而且我无法编写测试。
解决方案
而不是 forEach,使用普通的 for-loop 或 for-of 循环,因为您将孩子作为 HTMLCollection
const children = htmlContent.getElementsByClassName('document-content')[0].children;
for (let item of children) {
console.log(item);
}
推荐阅读
- c - 为什么`pthread_rwlock_t`的ABI在不同版本之间有很大差异?
- google-apps-script - 无法获取部署 ID 错误的详细信息
- java - java.lang.NoClassDefFoundError: java/sql/Date
- azure - 如何在 Azure Kubernetes 服务上模拟可用区中断?
- javascript - react如何将事件绑定到map生成的元素
- python - 可以从 Anaconda 的 Scripts 文件夹中安全地删除 .conda_trash 文件吗?
- bash - 文件有行,前 2 行变为 1 行,后 2 行变为 1 行
- javascript - 如何按升序替换另一个数组中未找到的元素的值?
- java - 使用 ResteasyClient 发送的日志请求
- iframe - 成功登录后 Iframe 中的 Jasper 服务器 webapp 注销(Chrome/Edge 浏览器)