检查HTML代码段是否对Javascript有效 [英] Check if HTML snippet is valid with Javascript

查看:84
本文介绍了检查HTML代码段是否对Javascript有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个可靠的Javascript库/函数来检查HTML代码段是否有效,我可以从我的代码中调用。例如,它应该检查打开的标记和引号是否关闭,嵌套是否正确等。



我不希望验证失败,因为某些不是100 %标准(但无论如何会起作用)。

解决方案

更新:此答案有限 - 请参阅在下面的编辑。



扩展@ kolink的答案,我使用:

  var checkHTML = function(html){
var doc = document.createElement('div');
doc.innerHTML = html;
return(doc.innerHTML === html);
}

即,我们用HTML创建一个临时div。为了做到这一点,浏览器将创建一个基于HTML字符串的DOM树,这可能涉及到关闭标签等。



比较div的HTML内容和原始HTML将告诉我们浏览器是否需要更改任何内容。

  checkHTML('< a>地狱< b> o< / b> ;')

返回false。

  checkHTML('< a> hell< b> o< / b>< / a>')

返回true。



编辑:@Quentin注释如下,过分由于各种原因,浏览器通常会修正省略的结束标记,即使结束标记对于该标记是可选的。例如:

 < p>一个段落
< p>第二段落

$ b

...被认为是有效的(因为Ps允许省略结束标记),但 checkHTML 将返回false。浏览器还会标记标记案例,并改变空白区域。决定使用这种方法时应该意识到这些限制。

I need a reliable Javascript library / function to check if a HTML snippet is valid that I can call from my code. For example, it should check that opened tags and quotation marks are closed, nesting is correct, etc.

I don't want the validation to fail because something is not 100% standard (but would work anyways).

解决方案

Update: this answer is limited - please see the edit below.

Expanding on @kolink's answer, I use:

var checkHTML = function(html) {
  var doc = document.createElement('div');
  doc.innerHTML = html;
  return ( doc.innerHTML === html );
}

I.e., we create a temporary div with the HTML. In order to do this, the browser will create a DOM tree based on the HTML string, which may involve closing tags etc.

Comparing the div's HTML contents with the original HTML will tell us if the browser needed to change anything.

checkHTML('<a>hell<b>o</b>')

Returns false.

checkHTML('<a>hell<b>o</b></a>')

Returns true.

Edit: As @Quentin notes below, this is excessively strict for a variety of reasons: browsers will often fix omitted closing tags, even if closing tags are optional for that tag. Eg:

<p>one para
<p>second para

...is considered valid (since Ps are allowed to omit closing tags) but checkHTML will return false. Browsers will also normalise tag cases, and alter white space. You should be aware of these limits when deciding to use this approach.

这篇关于检查HTML代码段是否对Javascript有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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