0

I have a form with several input fields including WYSIWYG editor as an input field. In WYSIWYG editor user enter data using HTML table. 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? How can I identify that within or in table tag (<table) exist. Any help would be appreciated.

1 Answers1

0

You can create an element out of your HTML like this:

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

JBS
  • 993
  • 5
  • 11