Contact!

Valid HTML element tag check: JavaScript

Valid html check

Since I started making web components I’ve come across a few use cases for checking for valid HTML elements.

It turns out that this is fairly easy to do. By creating an element and then converting it to a string representation we can match against “[object HTMLUnknownElement]” to check whether an element has been registered to customElements or exists by default.

function validHTML(element) {
    return document.createElement(element.toUpperCase()).toString() != "[object HTMLUnknownElement]";
}

validHTML('div') // returns true
validHTML('dog') // returns false
validHTML('registeredComponent') // returns true

For example, if we remove the boolean operator and just return the string we would get the following:

validHTML('div') // returns [object HTMLDivElement]
validHTML('dog') // returns [object HTMLUnknownElement]
validHTML('registeredComponent') // returns [object HTMLElement]

Join the discussion!

You might like: