Check if HTML Tag is Valid
const isTag = tag => {
return !/Unknown/.test(document.createElement(tag) + '')
}
console.log('section:', isTag('section'))
console.log('div:', isTag('div'))
console.log('nav:', isTag('nav'))
console.log('banana:', isTag('banana'))
Check if a tagName
is a valid html element.
When casting a dom node to a string, you’ll get a class name like this:
document.createElement('div') + ''
// '[object HTMLDivElement]'
// you can cast to a string with `toString` if
// you want things to be more readable
document.createElement('section').toString()
// '[object HTMLElement]'
document.createElement('input') + ''
// '[object HTMLInputElement]'
When you try to create something with an unknown tagName
you’ll end up with:
document.createElement('banana') + ''
// '[object HTMLUnknownElement]'
So, testing for the presence of the string Unknown
is an easy way to check if a tagName
is valid in a given browser. This is the perfect kind of thing to memoize:
const tags = {}
const isTag = tag => {
if (tags[tag] != null) {
// already calculated
console.log('loking up: ', tag, tags[tag]);
return tags[tag]
}
const result = !/Unknown/.test(document.createElement(tag) + '')
tags[tag] = result
return result
}
console.log('calculator', isTag('calculator'))
console.log('calculator', isTag('calculator'))
console.log('strong', isTag('strong'))
console.log('strong', isTag('strong'))