how to determine whether string is a valid html4 tagName?
Question by cc young
given a string, ‘div’ or ‘abc’, is there any way to determine whether the string is a valid html4 tagName?
tried using document.createElement()
, but it’s happy with anything:
document.createElement('trash')
=> <trash></trash>
cannot use HTML<tag>Element
. for example
document.createElement('tbody')
=> HTMLTableSelectorElement
Answer by minitech
The best way is to have a list of all valid HTML4 elements and check that. This will give you the right result for “a valid HTML4 element” 100% of the time. From here:
var html4 = ["A","ABBR","ACRONYM","ADDRESS","APPLET","AREA","B","BASE","BASEFONT","BDO","BIG","BLOCKQUOTE","BODY","BR","BUTTON","CAPTION","CENTER","CITE","CODE","COL","COLGROUP","DD","DEL","DFN","DIR","DIV","DL","DT","EM","FIELDSET","FONT","FORM","FRAME","FRAMESET","H1","H2","H3","H4","H5","H6","HEAD","HR","HTML","I","IFRAME","IMG","INPUT","INS","ISINDEX","KBD","LABEL","LEGEND","LI","LINK","MAP","MENU","META","NOFRAMES","NOSCRIPT","OBJECT","OL","OPTGROUP","OPTION","P","PARAM","PRE","Q","S","SAMP","SCRIPT","SELECT","SMALL","SPAN","STRIKE","STRONG","STYLE","SUB","SUP","TABLE","TBODY","TD","TEXTAREA","TFOOT","TH","THEAD","TITLE","TR","TT","U","UL","VAR"];
var valid = html4.indexOf(name.toUpperCase()) !== -1;
(Or, using an object, as @SLaks suggested.)
If you absolutely don’t want to do that for some reason, or didn’t actually mean HTML4, and aren’t worried about IE8- compatibility, then you can do this:
var valid = !(document.createElement(name) instanceof HTMLUnknownElement);
Answer by Starx
A rather simple technique is to define your own set of valid HTML Elements
Array.prototype.contains = function(k) {
return (this.indexOf(k) > -1;
}
var ValidTags = ['html', 'head', ....];
//Then compare
if(ValidTags.contains('trash')) {
//Then its valid
}