2

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!

3
  • 1
    Create an array of valid tag names, check the string against that array
    – tymeJV
    Oct 9, 2014 at 19:43
  • You can get a list of valid tag names here. Why not store them in an array in IsValid and compare Str to each element? Oct 9, 2014 at 19:43
  • I know this solution . But is there a better method? Oct 9, 2014 at 19:47

5 Answers 5

13

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.

1
  • Thanks for the answer. I use already createElement in my project, therefore it is a gut solution for my function. Oct 9, 2014 at 20:26
0

You will have to get and use your own array of HTML tags to check this - I would personally go with W3C spec instead of the w3schools one.

Then, you want to use indexOf on the array and check if it's not -1, something like this:

var isValid = function (tagCandidate) { return (validHtmlTags.indexOf(tagCandidate) > -1); };

0

Just a fast way to test tag names incase someone needs it.

First create a case insensitive set. So you don't need to worry about case when testing a string.
Answer borrowed from Jonas Wilms

class CaseInsensitiveSet extends Set {
    constructor(values){
        super(Array.from(values, it => it.toLowerCase()));
    }; 
    
    add(str) {
        return super.add(str.toLowerCase());
    }; 
    
    has(str) {
        return super.has(str.toLowerCase());
    }; 
    
    delete(str) {
        return super.delete(str.toLowerCase());
    }; 
}; 

Then create a set using his new class and all the tag name. Don't worry all current tags are here.

var TagNames = new CaseInsensitiveSet(`a,abbr,acronym,abbr,address,applet,embed,object,area,article
,aside,audio,b,base,basefont,bdi,bdo,big,blockquote,body,br,button,canvas,caption,center,cite
,code,col,colgroup,data,datalist,dd,del,details,dfn,dialog,dir,ul,div,dl,dt,em,embed,fieldset
,figcaption,figure,font,footer,form,frame,frameset,h1 to <h6>,head,header,hr,html,i,iframe,img
,input,ins,kbd,label,legend,li,link,main,map,mark,meta,meter,nav,noframes,noscript,object,ol
,optgroup,option,output,p,param,picture,pre,progress,q,rp,rt,ruby,s,samp,script,section,select
,small,source,span,strike,del,s,strong,style,sub,summary,sup,svg,table,tbody,td,template,textarea
,tfoot,th,thead,time,title,tr,track,tt,u,ul,var,video,wbr`.split(",")); 

Ok now you can use the built in has function to get the result in O(1).

TagNames.has("A") 
// returns true 
TagNames.has("a") 
// returns true 
TagNames.has("tAblE") 
// returns true 
0

Acknowledgement to Stryner upon whose answer this builds.

Firstly, I don't want to presuppose anything about your input. It might not even be a lexically-valid tag name, let alone one the browser understands. Perhaps it's not even a string? An invalid argument to document.createElement() will cause an error, so I catch this and return false.

function isValid(input) {
  try {
    return document.createElement(input).constructor.name !== 'HTMLUnknownElement';
  } catch(e) {
    return false;
  }
}

console.log(isValid('h1'));  //known tag name
console.log(isValid('wibble'));  //not known tag name
console.log(isValid('12'));  //not valid tag name
console.log(isValid(false)); //not even a string

Secondly, I have observed that, in Firefox at least, document.createElement() with an argument that contains hyphens will return not a HTMLUnknownElement but rather a HTMLElement. (I assume the reason for this is to do with support for Web Components / Custom Elements, but I cannot find further reading that explains the behaviour here.) I will boldly assume you do not want to allow these either.

function isValid(input) {
  try {
    const el = document.createElement(input);
    return el.constructor.name !== 'HTMLUnknownElement' &&
      el.constructor.name !== 'HTMLElement';
  } catch(e) {
    return false;
  }
}

console.log(isValid('h1'));  //known tag name
console.log(isValid('wibble'));  //not known tag name
console.log(isValid('wibble-wibble'));  //not known but returns a HTMLElement
console.log(isValid('12'));  //not valid tag name
console.log(isValid(false)); //not even a string

-1

Get a list of valid HTML tags (or whatever you want to compare with) and simply do something like:

function IsValid(s) {
    var tags = ['a', 'p', 'etc...'];
    return tags.indexOf(s) != -1;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.