)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Check if HTML Tag is Valid

  1. const isTag = tag => { 
  2.   return !/Unknown/.test(document.createElement(tag) + '')
  3. }
  4.  
  5. console.log('section:', isTag('section'))
  6. console.log('div:', isTag('div'))
  7. console.log('nav:', isTag('nav'))
  8. 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:

  1. document.createElement('div') + ''
  2. // '[object HTMLDivElement]'
  3.  
  4. // you can cast to a string with `toString` if 
  5. // you want things to be more readable
  6. document.createElement('section').toString()
  7. // '[object HTMLElement]'
  8.  
  9. document.createElement('input') + ''
  10. // '[object HTMLInputElement]'

When you try to create something with an unknown tagName you’ll end up with:

  1. document.createElement('banana') + ''
  2. // '[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:

  1. const tags = {}
  2. const isTag = tag => { 
  3.   if (tags[tag] != null) {
  4.     // already calculated
  5.     console.log('loking up: ', tag, tags[tag]);
  6.     return tags[tag]
  7.   }
  8.   const result = !/Unknown/.test(document.createElement(tag) + '')
  9.   tags[tag] = result
  10.   return result
  11. }
  12.  
  13. console.log('calculator', isTag('calculator'))
  14. console.log('calculator', isTag('calculator'))
  15.  
  16. console.log('strong', isTag('strong'))
  17. console.log('strong', isTag('strong'))
// dom // html // javascript // regex // strings // tricks // ui
snippet.zone ~ 2021-24 /// {s/z}