简体   繁体   English

验证所见即所得编辑器在 Javascript 中生成的 HTML 表

[英]Validation of HTML table generated by WYSIWYG editor in Javascript

I have a form with several input fields including WYSIWYG editor as an input field.我有一个包含多个输入字段的表单,包括所见即所得编辑器作为输入字段。 In WYSIWYG editor user enter data using HTML table.在所见即所得编辑器中,用户使用 HTML 表格输入数据。 But sometime happen while adding new row user enter new table snippet within in the same row as in the below code.但是有时会在添加新行时发​​生,用户在与下面的代码相同的行中输入新的表格片段。

<table width="100%">
<tbody>
    <tr>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td>
        <table width="100%">
            <tbody>
                <tr>
                    <td></td>
                    <td></td>
                </tr>
            </tbody>
        </table>
        </td>
    </tr>
</tbody>

How can I validate this HTML code snippet using Javascript?如何使用 Javascript 验证此 HTML 代码片段? How can I identify that within or in table tag (<table) exist.如何识别在表标签(<table)内或表内是否存在。 Any help would be appreciated.任何帮助,将不胜感激。

You can create an element out of your HTML like this:您可以像这样从 HTML 中创建一个元素

function htmlToElement(html) {
    var template = document.createElement('template');
    html = html.trim(); // Never return a text node of whitespace as the result
    template.innerHTML = html;
    return template.content.firstChild;
}

const myTable = htmlToElement('<table width="100%">....</table>');

... and then check if there is a table within the table: ...然后检查表内是否有表:

if (myTable.querySelector('table')) {
    // ...
}

Credits for the htmlToElement function: Creating a new DOM element from an HTML string using built-in DOM methods or Prototype htmlToElement 函数的功劳: 使用内置 DOM 方法或 Prototype 从 HTML 字符串创建新的 DOM 元素

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

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