Sort HTML attributes with JavaScript

html, javascript, regex

Solution

If you really must... try this fiddle. I have to say though, I'm really curious why you would want to do this.

Code:

var elements = document.getElementsByTagName("*");
sortAttributes(elements);

//From: http://stackoverflow.com/questions/979256/how-to-sort-an-array-of-javascript-objects
function sortBy(field, reverse, primer) {
    var key = function(x) {
        return primer ? primer(x[field]) : x[field];
    };

    return function(a, b) {
        var A = key(a),
            B = key(b);
        return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1, 1][+ !! reverse];
    }
};

function sortAttributes(elements) {
    for (var j = 0; j < elements.length; j++) {
        var attributes = [];
        for (var i = 0; i < elements[j].attributes.length; i++) {
            attributes.push({
                'name': elements[j].attributes[i].name,
                'value': elements[j].attributes[i].value
            });
        }

        var sortedAttributes = attributes.sort(sortBy('name', true, function(a) {
            return a.toUpperCase();
        }));

        for (var i = 0; i < sortedAttributes.length; i++) {
            $(elements[j]).removeAttr(sortedAttributes[i]['name']);
        }

        for (var i = 0; i < sortedAttributes.length; i++) {
            $(elements[j]).attr(sortedAttributes[i]['name'], sortedAttributes[i]['value']);
        }
    }
}

Problem

How would I sort HTML attributes using JavaScript? I have this HTML: ``` <table> <tbody> <tr> <td>Cell 0,0</td> <td>Cell 1,0</td> <td>Cell 2,0</td> </tr> <tr> <td>Cell 0,1</td> <td rowspan="2" colspan="2">Cell 1,1 <br>Cell 2,1 <br>Cell 1,2 <br>Cell 2,2</td> </tr> <tr> <td>Cell 0,2</td> </tr> </tbody> </table> ``` And I want to sort all attribute in all elements into alphabetical order. E.g: ``` <td colspan="2" rowspan="2">Cell 1,1 ``` The sort function could either be based on a HTML string, or a jQuery object, or a node (it doesn't matter which one). The reason I need this is because I am doing a diff (with JS, in the browser, after a failed unit test) between 2 sets of HTML and the attribute order is making it fail. So my questions are: How can I reorder a nodes attributes?, Or how can I reorder attributes in an HTML string?, Or how can I reorder a jQuery elements attributes? I haven't got any code for it yet, as I am unsure which method would be the best.

Original source

Related problems