Ordering List Alphabetically

I have one question. I need to create a javascript to order an unordered list alphabetically. I've achieved this with the following function:

$(function () {
    var $list = $(document.getElementsByClassName("list"));
    $list.children().detach().sort(function (a, b) {
        return $(a).text().localeCompare($(b).text());
    }).appendTo($list);
});

However, in the customer's design there are a few items on these lists that are other item's "child", with the following setup:

<ul>
    <li>alpha</li>
    <li>gama</li>
    <li>beta</li>
    <li style="margin-right: 5px;">beta1</li>
</ul>

On the code all of the items are inside the same list, however for the user, "beta1" is a little bit to the right, and combining with other styles, it makes it look like it's a child item.

With my function above, it's going to sort all items. In other words, "beta1" will be sorted together with the "parents".

I tried a few things with no success, so does anybody have any idea how can I achive this? i.e. my function needs to check if a list item has a style applied, if yes it's going to append it to the previous list item and order it as a one.

Thanks!

Upvotes: 1

Views: 73

Answers (1)

Ryan Dantzler
Ryan Dantzler

Reputation: 1144

How about changing your list structure to include the child list and then add a style for child lists.

<ul>
  <li>alpha</li>
  <li>gama</li>
  <li>beta
    <ul>
      <li>beta1</li>
    </ul>
  </li>
</ul>

CSS:

li ul {
  margin-right: 5px;
}

Upvotes: 1

Related Questions