验证字符串是否是有效的HTML标记名称 [英] Verify whether a string is a valid HTML tag name

查看:230
本文介绍了验证字符串是否是有效的HTML标记名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查看字符串是否是有效的HTML标签?

How can I find out if a string is a valid HTML tag?

例如:a或h1,div或span,...是有效的HTML标记名。
但是ar或abc或div2,...都是invaild。

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
}

谢谢。

PS
我想,这不是一个愚蠢的问题,我在这里找到了一个很好的解决方案(见下面)。但我不知道为什么这个线程有-3?想想!

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!

推荐答案

HTML5引入了 HTMLUnknownElement界面,必须用于未由标准HTML规范定义的元素。

HTML5 introduced the HTMLUnknownElement interface which must be used for elements that are not defined by the standard HTML specifications.

使用 document.createElement ,如果元素不是一个有规范的有效标签,它将是一个HTMLUnknownElement类型的对象。由于使用 .toString 将返回 [object type] ,您可以创建该类型的元素并进行测试:

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]";
}

alert(isValid("tr"));
alert(isValid("a"));
alert(isValid("trs"));
alert(isValid("strong"));
alert(isValid("strongg"));

但是,这很多在老版本的浏览器中无效。

However, this many not work in older browsers.

这篇关于验证字符串是否是有效的HTML标记名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆