Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify whether a string is a valid HTML tag name

Tags:

jquery

dom

How can I find out if a string is a valid HTML tag?

For example: a, or h1, div, or span, ... are a valid HTML tagname. But ar, or abc, or div2, ... are invaild.

var Str = 'strongg';

if( IsValid(Str) ) {
// do something
}

Thanks.

PS I think, this was not a stupid question and I found a good solution for it here (see below). But I do not know why this thread has "-3" ? Wondering!

like image 309
user3417601 Avatar asked May 06 '26 20:05

user3417601


1 Answers

HTML5 introduced the HTMLUnknownElement interface which must be used for elements that are not defined by the standard HTML specifications.

When using document.createElement, if the element is not a valid tag by specification, it will be an object of type HTMLUnknownElement. Since using .toString will return [object type], you can create the element and test for that type:

function isValid(input) {
  return document.createElement(input).toString() != "[object HTMLUnknownElement]";
}

console.log( isValid("tr") );
console.log( isValid("a") );
console.log( isValid("trs") );
console.log( isValid("strong") );
console.log( isValid("strongg") );

However, this many not work in older browsers.

like image 139
Stryner Avatar answered May 09 '26 10:05

Stryner