检查 HTML 片段是否对 JavaScript 有效 [英] Check if HTML snippet is valid with JavaScript

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

问题描述

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

I need a reliable JavaScript library / function to check if an 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.

我不希望验证失败,因为某些东西不是 100% 标准的(但无论如何都可以).

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

推荐答案

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

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

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

Expanding on @kolink's answer, I use:

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

即,我们使用 HTML 创建一个临时 div.为此,浏览器将根据 HTML 字符串创建一个 DOM 树,其中可能涉及结束标记等.

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.

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

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>')

返回错误.

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

返回真.

正如@Quentin 在下面指出的那样,出于多种原因,这过于严格:浏览器通常会修复省略的结束标记,即使结束标记是可选的那个标签.例如:

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

...被认为是有效的(因为 Ps 可以省略结束标记)但 checkHTML 将返回 false.浏览器还将规范化标签大小写,并改变空白.在决定使用这种方法时,您应该了解这些限制.

...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天全站免登陆