简体   繁体   English

使用 javascript/jquery 验证 html 语法

[英]validate html syntax using javascript/jquery

how do I validate a string of html using javascript/jquery eg of html string如何使用 html 字符串的 javascript/jquery 验证 html 的字符串

   <style type="text/css">     
     .nai {position:absolute;top:0px;right:0px;z-index:90000;
      background-image:url("http://example.com/test.png");
      background-repeat:no-repeat;width:19px;height:15px;}

     .nai:hover {width: 77px;
      background-image:url("http://example.com /test.png");}
    </style>
   <div style="width:160px;height:600px;position:absolute"></div>

am looking for basic validations like.whether start/end tag is proper or not我正在寻找基本的验证,比如开始/结束标签是否正确

tried using jquery's fns as follows尝试使用 jquery 的 fns 如下

  var $str1 = $(str1); // html string into real html 

  var len = $str1.length;
    // console.log($str1);
    for(var i=0;i<len;i++){
      if(typeof $($str1[i]).get(0).outerHTML!='undefined'){
        final1+=unescapeHtml($($str1[i]).get(0).outerHTML);
      }

   }

but above code doesnt validate & rectify child elments tag/or start tag of an element if absent.但上面的代码不会验证和纠正子元素标签/或元素的开始标签(如果不存在)。

There is no out-of-the-box solution for validating (or parsing) HTML with JavaScript, and you can't just abuse DOM for that purpose. 没有使用JavaScript验证(或解析)HTML的即用型解决方案,并且您不能仅出于此目的滥用DOM。
You would have find some 3rd party library (like the one from Dagriel 's answer) or write a parser/validator yourself. 您将找到一些第三方库(例如Dagriel的答案中的库)或自己编写解析器/验证器。

You can validate that a string contains valid html syntax by using the DOMParser()您可以使用 DOMParser() 验证字符串是否包含有效的 html 语法

Example here: https://tonylea.com/checking-for-valid-html-strings-in-javascript此处示例: https://tonylea.com/checking-for-valid-html-strings-in-javascript

Take a look at: 看一眼:

https://github.com/peterjwest/html_validator https://github.com/peterjwest/html_validator

The aim of this project is this: 该项目的目的是:

  • To allow anyone on any browser be able to validate HTML, either using a bookmarklet or browser extension 为了使任何浏览器上的任何人都能够使用小书签或浏览器扩展来验证HTML
  • To support the major doctypes: HTML 4.01, XHTML 1.0 and eventually HTML 5 支持主要的文档类型:HTML 4.01,XHTML 1.0以及最终的HTML 5
  • To provide a plain English, sensible version of the W3C HTML spec 提供简单易懂的W3C HTML规范的英语版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM