Я извлек это решение одного из моих проектов:
const tagNameOf = (function () {
// This lookuptable is key to the solution, it must somehow be kept up to date
const elementNameLookupTable = {
'UList': ['ul'],
'TableCaption': ['caption'],
'TableCell': ['th', 'td'],
'TableCol': ['col', 'colgroup'],
'TableRow': ['tr'],
'TableSection': ['thead', 'tbody', 'tfoot'],
'Quote': ['q'],
'Paragraph': ['p'],
'OList': ['ol'],
'Mod': ['ins', 'del'],
'Media': ['video', 'audio'],
'Image': ['img'],
'Heading': ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
'Directory': ['dir'],
'DList': ['dl'],
'Anchor': ['a']
};
return function (HTMLElementConstructor) {
let match; let tagName = [];
if (typeof HTMLElementConstructor === 'function') {
match = /HTML(\w+)Element/.exec(HTMLElementConstructor.name);
if (match) {
tagName = elementNameLookupTable[match[1]] || [match[1].toLowerCase()];
}
}
return tagName;
};
}());
// Test:
console.log(tagNameOf(HTMLAnchorElement));
console.log(tagNameOf(HTMLMediaElement));
console.log(tagNameOf(HTMLHeadingElement));
Следует отметить, что функция возвращает массив, поскольку существует более одного возможного соответствующего имени тега.