Tags can have multiple attributes. The order in which attributes appear in the code does not matter. For example:

<a href="#" title="#">
<a title="#" href="#">

How can I "normalize" the HTML in Javascript, so the order of the attributes is always the same? I don't care which order is chosen, as long as it is always the same.

UPDATE: my original goal was to make it easier to diff (in JavaScript) 2 HTML pages with slight differences. Because users could use different software to edit the code, the order of the attributes could change. This make the diff too verbose.

ANSWER: Well, first thanks for all the answers. And YES, it is possible. Here is how I've managed to do it. This is a proof of concept, it can certainly be optimized:

function sort_attributes(a, b) {
  if( a.name == b.name) {
    return 0;
  }

  return (a.name < b.name) ? -1 : 1;
}

$("#original").find('*').each(function() {
  if (this.attributes.length > 1) {
    var attributes = this.attributes;
    var list = [];

    for(var i =0; i < attributes.length; i++) {
      list.push(attributes[i]);
    }

    list.sort(sort_attributes);

    for(var i = 0; i < list.length; i++) {
      this.removeAttribute(list[i].name, list[i].value);
    }

    for(var i = 0; i < list.length; i++) {
      this.setAttribute(list[i].name, list[i].value);
    }
  }
});

差值的第二个元素也是如此,$('#different').现在,$('#original').html()$('#different').html()显示了具有相同顺序的属性的HTML代码.

推荐答案

This is a proof of concept, it can certainly be optimized:

function sort_attributes(a, b) {
  if( a.name == b.name) {
    return 0;
  }

  return (a.name < b.name) ? -1 : 1;
 }

$("#original").find('*').each(function() {
  if (this.attributes.length > 1) {
    var attributes = this.attributes;
    var list = [];

    for(var i =0; i < attributes.length; i++) {
      list.push(attributes[i]);
    }

     list.sort(sort_attributes);

    for(var i = 0; i < list.length; i++) {
      this.removeAttribute(list[i].name, list[i].value);
    }

     for(var i = 0; i < list.length; i++) {
       this.setAttribute(list[i].name, list[i].value);
    }
  }
 });

Same thing for the second element of the diff, $('#different'). Now $('#original').html() and $('#different').html() show HTML code with attributes in the same order.

Jquery相关问答推荐

如何用each替换元素的attr href

如何在不使用点击事件 bootstrap 程序模式的情况下使用弹出窗口 bootstrap 程序显示用户详细信息?

如何在没有实体框架的情况下在 ASP.NET 上使用 ajax 和 jquery 从列表创建数据表

为什么在 jQuery 插件中返回 this.each(function())?

Jquery each - 停止循环并返回对象

Ajax 替换而不是追加

jQuery .val() 和 .attr('value') 有什么区别?

如何以十六进制获取元素的背景 colored颜色 代码?

如何用 javascript/jquery 替换 url 参数?

如何将 JavaScript 对象编码为 JSON?

如何使用 jQuery 的 getJSON() 方法传递请求标头?

jQuery: Select 属性大于值的所有元素

使用 bootstrap-datepicker 检测对选定日期的更改

Rails,单击link_to helper后未加载javascript

在 jQuery 中将 JSON 数组转换为 HTML 表

使用 jQuery Select 焦点文本在 Safari 和 Chrome 中不起作用

jQuery Force 为 iframe 设置 src 属性

offsetTop 与 jQuery.offset().top

jQuery:如何找到父母的特定子元素?

由于滚动,响应表内的 bootstrap 按钮下拉菜单不可见