1

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

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

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

不能使用HTML<tag>Element。例如

document.createElement('tbody')
=> HTMLTableSelectorElement
4

3 回答 3

6

最好的方法是列出所有有效的 HTML4 元素并进行检查。这将为您提供 100% 的“有效 HTML4 元素”的正确结果。从这里

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);
于 2013-01-20T03:00:22.257 回答
1

正在寻找解决方案,但更完整。下面的片段是围绕 Stack 和 Google 搜索的最终结果。它不像那里的 HTML4 数组检查那么简单,但也没有那么复杂。

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

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

还有一件事!作为第二个参数传递-1以完全绕过过时的检查。过时检查是根据W3C HTML5 标准组成的数组执行的,该数组说明截至 2014 年 10 月 28 日哪些标签已过时。

一点额外的。只是添加了一点,如果您尝试传入 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>

于 2015-03-13T13:49:46.240 回答
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
}
于 2013-01-20T03:02:39.963 回答