Correct Improper HTML with jQuery

Correct Improper HTML with jQuery

I'm developing a site in Wordpress for clients who have ZERO html skills. One of the problems which has cropped up a couple of times, is that they have somehow managed to insert improper, unlabeled/empty DIV tags into the post content, and it's not surprisingly breaking the site's page formatting.

I have searched far and wide, and utilized quite a bit of trial and error to find a way for jQuery to solve this problem for me, but I'm as yet only partially there. Assume this sample HTML:

  1. <div id="the_content">
  2.       <div><p>First paragraph</p></div>
  3.       <p>Second Paragraph</p>
  4.       <div>
  5. </div>
In the example above, I would either like to add the closing div to the tag after the second paragraph, or simply strip all three of the div tags contained within "the_content" completely out of the code, leaving all the other html formatting intact. To this end, I have written the following two jQuery functions, each with only partial success:

  1. /*This function still only informational at this point and 
  2. is meant to count the empty divs within "the_content" and identify the
  3. closing divs that remain as well. It correctly identifies the number of opening div tags
  4. but is not written correctly to identify the number of closing div tags.
  5. Once I have this function working properly, my plan was to somehow compare the 
  6. values of each of the numbers, and add the appropriate tag "foreach" numerical difference */

  7. var opening_divs = jQuery("#the_content div:not([class]), #the_content div:not([id])").length;
  8. var closing_divs = jQuery('#the_content:contains("</div>")').length;
  9. jQuery("span").append("<p>There are " + opening_divs + " opening divs.");
  10. jQuery("span").append("<p>There are " + closing_divs + " closing divs.");

As you experts will note, the above isn't written entirely correctly. I'm able to get an accurate count of the opening div tags, but I can't find a way to properly identify the straggling closing div tags. Further to that, I don't really know how I'd write the function to add tags using an iterative "foreach" function should that turn out to be the solution.

The other function I've had partial success with is the following, but it also still leaves the stragglers:

  1. /*This function successfully strips the empty divs that open and close, 
  2. but unfortunately still leaves any improper/un-closed divs in place*/
  3. jQuery('#the_content div:not([class]), #the_content div:not([id])').each(function () {
  4. jQuery(this).replaceWith(jQuery(this.childNodes));
  5. });

Thank in advance for your help.