Ideally, you would use a function like this:
function checkTable(tableElement) {
// Get inner HTML
var html = tableElement.innerHTML;
// Count <tr>
var count1 = html.match(/<tr/g).length;
// Count </tr>
var count2 = html.match(/<\/tr/g).length;
// Equals?
return count1 === count2;
}
However, due to browser's mumbo-jumbo, the mismatched tags get auto-corrected (i.e. auto-closed). Therefore it is impossible for a running page to validate itself. Here is a proof of concept: JS Bin.
Explanation: The second table has a typo (opening tag instead of a closing tag), but the function returns true in both cases. If one inspects the generated HTML (the one that is accessible through DOM), one can see that the browser auto-corrected the mismatched tags (there is an additional empty table row).
Luckily, there is another way. To obtain the pure (i.e. not modified by the browser) HTML code, you can make an AJAX request to the current page URL. Yes, you read correctly - the page loads itself again. But no worries, there is no recursion and possible stackoverflow here, since you do not process the fetched page.
The JS code for the following is:
var selfUrl = document.location.href;
function checkHTML(html) {
// Count <tr>
var count1 = html.match(/<tr/g).length;
console.log(count1);
// Count </tr>
var count2 = html.match(/<\/tr/g).length; // </tr (do not remove this comment!)
console.log(count2);
// Equals?
return count1 === count2;
}
$.get(selfUrl, function(html) {
console.log(checkHTML(html));
});
But beware of one pitfall. If you include this code in the HTML itself (usually discouraged), then you must not remove that one comment. The reason is the following: one regex contains <tr, while the other has the forward slash escaped and does therefore not contain a </tr. And since you fetch the whole HTML code (including the JS code), the count is mismatched. To even this, I have added an additional </tr inside a comment.
innerHTMLof the table and then use regex to count both start and endtrtags. But if HTML structure is not proper (i.e. missing end tags), nobody knows what can happen.