Check if HTML snippet is valid with JavaScript

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

Expanding on @kolink’s answer, I use:

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

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.

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

Returns false.

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

Returns true.

Edit: 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

…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.

Leave a Comment