Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a diff of two DOM elements (rather than two strings) in javascript

This works really well for strings: http://ejohn.org/projects/javascript-diff-algorithm/

And I used to do string diffing server side (in ruby), but It's really hard to also take into consideration forced tag structure, like in tables.

What I did with just non table html was too add spans around the added and deleted text / inline elements. That method works well until you start trying to diff groups of TDs.

So, is there any Javascript library out there that will generate a visual diff with tables?

UPDATE / Example:

Table1:                    Table 2:

<table>                     <table>
    <tr>                        <tr>
        <td>sometext</td>           <td>some <b>text</b></td>
        <td>moretext</td>           <td><b>more text</b></td>
    </tr>                       <tr>
</table>                    </table>

Resulting Table (just a possibility, as there are many ways to show diffs)

<table>
    <tr>
        <td>some<del>text</del><add> <b>text</b></add></td>
        <td><del>more text</del><add><b>more text</b></add></td>
    </tr>
</table>
like image 327
NullVoxPopuli Avatar asked Feb 27 '12 17:02

NullVoxPopuli


1 Answers

Here is my initial attempt. It uses the diff library that you referenced and assumes that the tables are of the same dimensions.

$(document).ready(function() {
    $("#tbl1 tbody").children("tr").each(function(rownum, tr) {
        _tr = $("<tr>");
        tr2 = $($("#tbl2 tbody tr").get(rownum));
        $(tr).children("td").each(function(colnum, td) {
            text = $(td).html();
            text2 = $($(tr2).children("td").get(colnum)).html();
            _tr.append("<td>" + diffString(text, text2) + "</td>");
        });
        $("#results").append(_tr);
    });
});​

http://jsfiddle.net/SPSJb/

like image 62
jasonlfunk Avatar answered Oct 16 '22 17:10

jasonlfunk