Pergunta

I have a simple definition list in HTML and I need it sorted alphabetically based on DT value.

<dl>
    <dt>fruit</dt>
    <dd>apple, orange, bannana</dd>
    <dt>vegetable</dt>
    <dd>tomato, lettuce</dd>
<dl>
Foi útil?

Solução 2

Actually we apply sorting on elements that are belonging to particular category.

In your case under <dl>, you can apply sorting to either <dt> or <dd> dom elements.

For such sorting you may use tinysort jquery plugin, refer to link

You may refer to fiddle link for sorting in descending order.

Note: You can change the order.

Outras dicas

Without any additional plugins or libraries it can be simply achieved by putting <dd>'s inside <dt>'s, sorting <dt>'s and then putting <dd>'s back out.

var dl = $("#my-list");
$(dl).children('dt').each(function() {
    $(this).append($(this).next());
});
var sortedItems = $(dl).children('dt').sort();
$.each(sortedItems, function(i, dt) {
    $(dl).append(dt);
    $(dt).children('dd').each(function(j, dd) {
        $(dl).append($(dd));
    });
});

Solution offered by @Mazzu is probably cleaner and better. Thx.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top