JQuery wraps around poorly formatted HTML code

I have very poorly formatted HTML where every element in the table is a row. I want to group subelements a bit by adding some HTML pages. Here is a small example of HTML:

<html> <head> <title>Test</title> </head> <body> <table width="100%"> <tr class="heading"> <td>value 1</td> </tr> <tr> <td>sub 1</td> </tr> <tr> <td>sub 1</td> </tr> <tr class="heading"> <td>value 2</td> </tr> <tr> <td>sub 2</td> </tr> <tr class="heading"> <td>value 3</td> </tr> <tr> <td>sub 3</td> </tr> </table> </body> </html>​ 

I would like to wrap each line with a heading class, with a different tr or div, or really something that will allow me to pick up on sub-elements a bit. I tried various combinations of before, html, etc., but I can't get this to work.

Here is the jsfiddle I put together. Any way to wrap tr values ​​with a header class? For example, I would like to capture 3 lines with the class title in the HTML example. I would like to add this first line with some HTML and close it before the start of the second line. I would repeat this process for each line (open the tag and close it to the next line), in the last line I just close it.

So I would like to get:

 <html> <head> <title>Test</title> </head> <body> <table width="100%"> <SOME_TAG> <tr class="heading"> <td>value 1</td> </tr> <tr> <td>sub 1</td> </tr> <tr> <td>sub 1</td> </tr> </SOME_TAG> <SOME_TAG> <tr class="heading"> <td>value 2</td> </tr> <tr> <td>sub 2</td> </tr> </SOME_TAG> <SOME_TAG> <tr class="heading"> <td>value 3</td> </tr> <tr> <td>sub 3</td> </tr> </SOME_TAG> </table> </body> </html>​ 
+4
source share
1 answer

Based on kssr suggestion - wrap them in subtables using nextUntil and wrapAll

 $(document).ready(function() { wrapTR(0); }); function wrapTR(index) { $('tr.heading:eq('+index+')').nextUntil('.heading').andSelf().wrapAll('<table class="useful-grouping" id="table-'+index+'"/>'); if($('tr.heading:eq('+index+')').next('.heading')) { wrapTR(index+1) } } 
+4
source

Source: https://habr.com/ru/post/1442394/


All Articles