0

I am using jQuery to sort a list of li tags, My current code is:

var arr = [];
$("ul li").each(function() {
    arr.push($(this));
});
arr.sort(cmpFunction);
$("ul").find("li").remove();
$.each(arr, function(index, item){
    console.log(item.html());
});

What i'm finding with the console.log though - is I am losing the outside containing li tag (with the html5 data attributes that I want to keep)

Is there another option to .html() that will give me the objects li tag as well

I have provided a simple example of what I need here: http://jsbin.com/esalas/5

Mark Willis
  • 1,711
  • 1
  • 14
  • 23

1 Answers1

6

There is no inbuilt function in jQuery to do this. The workaround is to wrap the element in another, and then get the html() of that:

$.each(arr, function(index, item) {
    var html = item.wrap("<div></div>").parent().html();
    console.log(html);
});

You could also revert back to native Javascript and use outerHTML - although I've not tested this:

$.each(arr, function(index, item) {
    console.log(item[0].outerHTML);
});
Jon Adams
  • 24,464
  • 18
  • 82
  • 120
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339