如何确定字符串是否是有效的html4 tagName?

时间:2013-01-20 02:57:41

标签: javascript html dom

给定一个字符串'div'或'abc',有没有办法确定该字符串是否是有效的html4 tagName?

尝试使用document.createElement(),但对任何事情都很满意:

document.createElement('trash')
=> <trash></trash>

无法使用HTML<tag>Element。例如

document.createElement('tbody')
=> HTMLTableSelectorElement

3 个答案:

答案 0 :(得分:6)

最佳方式是拥有所有有效HTML4元素的列表并检查它。这将在100%的时间内为您提供“有效的HTML4元素”的正确结果。 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;

如果您出于某种原因绝对不想这样做,或者实际上并不意味着HTML4,并且不担心IE8兼容性,那么您可以这样做:

var valid = !(document.createElement(name) instanceof HTMLUnknownElement);

答案 1 :(得分:1)

正在寻找解决方案,但更完整一点。下面的代码段是搜索Stack和Google的最终结果。它不像HTML4阵列检查那么简单,但也没有那么复杂。

方法很简单。调用它,将字符串作为参数传递,如果它是有效的HTML5标记,将返回true。到目前为止,它对我能想到的每个标签起作用。

还有第二个参数,名为“allowObsolete”。顾名思义,它允许像applet这样的过时标签也返回true,否则obsolete tags会自动返回false。

还有一件事!将-1作为第二个参数传递,以完全绕过过时的检查。根据截至2014年10月28日已废弃的标签W3C HTML5 Standards制作的数组,执行过时检查。

额外的一点。如果您尝试传入CSS选择器/比较符号,只需添加一小部分也会返回false。基本上任何不是字母数字字符的东西都会导致它返回false。如果你决定编辑,请记住,它不能仅限于alpha,因为tehre是像h1这样的标签。

简单代码段

/** isValidHTMLTag(String, Mixed Var)
 * 
 *  @description Simple and effective way of checking whether an string is a valid HTML Tag Name.
 *
 *  @note Not yet tested on all Browsers. Use discreetly.
 *
 *  @example isValidHTMLTag('input');   //  returns `true`
 *  @example isValidHTMLTag('blink');   //  returns `false` because `blink` is obsolete
 *  @example isValidHTMLTag('blink', true); //  returns `true`
 *  @example isValidHTMLTag('blink', -1);   //  returns `false` in an HTML5 browser
 *  
 *  @param {String} tagName *Required | The string to check for validity.
 *  @param {Boolean|Integer} Determine whether or not to allow possible Obsolete Tag Names to return true. Set to `-1` to completely bypass this option. [undefined==false]
 *  @returns {Boolean} `true` if valide, otherwise `false`
 */
function isValidHTMLTag(tagName, allowObsolete) {   //  use `-1` as second parameter to completely bypass allowObsolete check
    var obsolete = ['acronym', 'applet', 'basefont', 'bgsound', 'big', 'blink', 'center', 'dir', 'font', 'frame', 'frameset', 'hgroup', 'isindex', 'listing', 'marquee', 'multicol', 'nextid', 'nobr', 'noembed', 'noframes', 'plaintext', 'spacer', 'strike', 'tt', 'xmp'];
    return tagName.match(/[^a-zA-Z0-9]/) ? !1 : -1 !== allowObsolete && -1 !== obsolete.indexOf(tagName) ? allowObsolete || !1 : "[object HTMLUnknownElement]" !== Object.prototype.toString.call(document.createElement(tagName));
}

一个班轮!

function isValidHTMLTag(a,b){var c="acronym applet basefont bgsound big blink center dir font frame frameset hgroup isindex listing marquee multicol nextid nobr noembed noframes plaintext spacer strike tt xmp".split(" ");return a.match(/[^a-zA-Z0-9]/)?!1:-1!==b&&-1!==c.indexOf(a)?b||!1:"[object HTMLUnknownElement]"!==Object.prototype.toString.call(document.createElement(a))};
  

顽皮提示 修改DOM!使用以下

Object.defineProperty && !Element.prototype.hasOwnProperty("isValidTag") ? Object.defineProperty(Element.prototype, "isValidTag", {
        value: function(b) {
            if (this.tagName) {
                var c = "acronym applet basefont bgsound big blink center dir font frame frameset hgroup isindex listing marquee multicol nextid nobr noembed noframes plaintext spacer strike tt xmp".split(" "),
                    a = this.tagName;
                return a.match(/[^a-zA-Z0-9]/) ? !1 : -1 !== b && -1 !== c.indexOf(a.toLowerCase()) ? b || !1 : "[object HTMLUnknownElement]" !== Object.prototype.toString.call(document.createElement(a))
            }
            return !1
        }
    }) :
    Element.prototype.isValidTag = function(b) {
        if (this.tagName) {
            var c = "acronym applet basefont bgsound big blink center dir font frame frameset hgroup isindex listing marquee multicol nextid nobr noembed noframes plaintext spacer strike tt xmp".split(" "),
                a = this.tagName;
            return a.match(/[^a-zA-Z0-9]/) ? !1 : -1 !== b && -1 !== c.indexOf(a.toLowerCase()) ? b || !1 : "[object HTMLUnknownElement]" !== Object.prototype.toString.call(document.createElement(a))
        }
        return !1
    };

//  Use like:
var blinky = document.createElement('blink');
if (!blinky.isValidTag()) {
    var head = document.head || document.getElementsByTagName("head")[0],
        style = document.createElement("style");
    style.appendChild(document.createTextNode("@keyframes blink { from { opacity: 1; } to { opacity: 0; } }"));
    style.appendChild(document.createTextNode("@-webkit-keyframes blink { from { opacity: 1; } to { opacity: 0; } }"));
    style.appendChild(document.createTextNode("blink { -webkit-animation: blink 600ms infinite; animation: blink 600ms infinite; text-decoration: blink; }"));
    head.appendChild(style);
}

然后你可以做这样的片段!

Object.defineProperty&&!Element.prototype.hasOwnProperty("isValidTag")?Object.defineProperty(Element.prototype,"isValidTag",{value:function(b){if(this.tagName){var c="acronym applet basefont bgsound big blink center dir font frame frameset hgroup isindex listing marquee multicol nextid nobr noembed noframes plaintext spacer strike tt xmp".split(" "),a=this.tagName;return a.match(/[^a-zA-Z0-9]/)?!1:-1!==b&&-1!==c.indexOf(a.toLowerCase())?b||!1:"[object HTMLUnknownElement]"!==Object.prototype.toString.call(document.createElement(a))}return!1}}):
Element.prototype.isValidTag=function(b){if(this.tagName){var c="acronym applet basefont bgsound big blink center dir font frame frameset hgroup isindex listing marquee multicol nextid nobr noembed noframes plaintext spacer strike tt xmp".split(" "),a=this.tagName;return a.match(/[^a-zA-Z0-9]/)?!1:-1!==b&&-1!==c.indexOf(a.toLowerCase())?b||!1:"[object HTMLUnknownElement]"!==Object.prototype.toString.call(document.createElement(a))}return!1};

$('body > *:not(hr)').each(function(i) {
  $(this).find('.tag-name').text(this.tagName);
  $(this).find('.is-not').html('is' + (this.isValidTag(i==5?-1:null) ? '' : ' <b>NOT</b>'));
});
/* Standard (Mozilla) */
@keyframes blink { from { opacity: 1; } to { opacity: 0; } }
/* Chrome & Safari */
@-webkit-keyframes blink { from { opacity: 1; } to { opacity: 0; } }
blink { -webkit-animation: blink 600ms infinite; animation: blink 600ms infinite; text-decoration: blink; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</div>
<hr />
<blink>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</blink>
<hr />
<p>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</p>
<center>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal <sub>but is still supported in most browsers. Thus use the bypass param "-1"</sub></center>
<hr />
<center>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</center>
<hr />
<article>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</article>
<hr />
<header>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</header>
<hr />
<a href="javascript:void 0">Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</a>
<hr />
<penguin>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</penguin>
<hr />
<pre>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</pre>
<hr />
<footer>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</footer>
<hr />
<bob>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</bob>
<hr />
<h9>Tag Name [<b><span class="tag-name"></span></b>] [<i><span class="is-not"></span></i>] legal</h9>

答案 2 :(得分:0)

一种相当简单的技术是定义您自己的一组有效HTML元素

Array.prototype.contains = function(k) {
   return (this.indexOf(k) > -1;
}
var ValidTags = ['html', 'head', ....];
//Then compare
if(ValidTags.contains('trash')) {
   //Then its valid
}