考虑这个函数:
tagName => document.createElement(tagName).constructor
它返回具有特定标记名称的 HTML 元素的构造函数。
我想反转这个过程并获取 HTML 元素提供的构造函数的标签名称(或名称?)。我想对我正在编写的一些单元测试执行此操作,但可能还有其他用例。
一些例子:
tagNameOf(HTMLDivElement) // should be "div"
tagNameOf(HTMLIFrameElement) // should be "iframe"
tagNameOf(HTMLHtmlElement) // should be "html"
tagNameOf(HTMLTableRowElement) // should be "tr"
不幸的是,我不知道从哪里开始,除非使用静态映射。
有没有简单的方法可以实现这一点?
最佳答案
我认为一个看起来很脏的解决方案是检查构造函数的 toString()
:
const makeConstructor = tagName => document.createElement(tagName).constructor;
const constructorToTagName = constr => constr.toString().match(/HTML(\w+)Element/)[1].toLowerCase();
console.log(constructorToTagName(makeConstructor('div')));
console.log(constructorToTagName(makeConstructor('span')));
关于javascript - 来自构造函数的 HTML 元素标签名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51000461/