Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is valid html tag.

Tags:

javascript

Is there any Native Javascript Functions to check if html tag exists?

I mean :

 var tag = "div";
 alert(isValidTag(tag)) // true;
 alert(isValidTag("foo")) // false;

If there is no native function for that, I will keep my function :

function isValidTag(tagName) {
  var tags = ["div","span","a","link" ... "body"];
  for(var i=0, len = tags.length; i++ < len; ) {
    if(tags[i] == tagName) return true;
  }
  return false;
}
like image 329
John Avatar asked Nov 30 '25 05:11

John


2 Answers

No. JS has nothing HTML specific in it at all, and DOM doesn't add anything like that.

like image 61
Quentin Avatar answered Dec 02 '25 17:12

Quentin


This might not be as efficient, I haven't done any time trials on it, but it can still be a good alternative to having to maintain a list of all the possible values yourself.

var isHTML = (function() {
  var unknown = '[object HTMLUnknownElement]', overrides = {CANVAS:1,VIDEO:1}; //html5 elements. Some browsers don't support these.
  return function(tag) {
    return overrides[tag = tag.toUpperCase()] || (!overrides.hasOwnProperty(tag) && (overrides[tag] = (document.createElement(tag).toString() !== unknown)));
  };
})();

This method will first check for a cached result, and if there isn't one it will determine a result based on the browser's own document.createElement. If the browser doesn't support it then we can safely assume it isn't an html tag.

Some sample outputs:

isHTML('curve'); //false
isHTML('div'); //true
isHTML('DIV'); //true
isHTML('tbody'); //true
isHTML('object'); //true
isHTML('document'); //false
isHTML('html'); //true
isHTML('svg'); //false
isHTML('rect'); //false
like image 40
Sollace Avatar answered Dec 02 '25 19:12

Sollace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!