Is it possible to append a unique CSS class to multiple <li> elements, or re-sort them using Jquery?
-
08-01-2021 - |
Pregunta
Currently working on the Squarespace.com platform and I'd like to re-sort a dynamic Blog Category index that defaults to alphabetical sorting. This is how Squarespace generates the code:
<div id="moduleContentWrapper11663355" class="widget-wrapper widget-type-journalarchive">
<div id="moduleContent11663355">
<ul class="archive-item-list-pt">
<li>
<a href="/blog/category/category-one">Category One</a>
<span class="entry-count">(1)</span>
</li>
<li>
<a href="/blog/category/category-two">Category Two</a>
<span class="entry-count">(1)</span>
</li>
<li>
<a href="/blog/category/category-three">Category Three</a>
<span class="entry-count">(1)</span>
</li>
</ul>
</div>
</div>
Is it possible to re-sort the entries using Jquery, or worse case, can I append a unique CSS class to each <li>
so I can manipulate each one using CSS?
Thanks!
Solución
var i = 1;
$('.archive-item-list-pt li').each(function(item) {
$(item).addClass('myClass'+i);
});
Otros consejos
the dom is really nothing but a complicated collection... you can use jquery to sort the li like an array.
var mylist = $('#moduleContent11663355 > ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
var compA = $(a).text().toUpperCase();
var compB = $(b).text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });
thanks to http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/
$('.archive-item-list-pt li').each(function(i,j) {
$(this).addClass('yourClass'+i);
});
here is the fiddle http://jsfiddle.net/h2gfT/7/
update
$('.archive-item-list-pt li').each(function(i,j) {
var cls=$(this).children("a").text().toLowerCase();
var idx = cls.replace(' ','-');
$(this).addClass(idx);
});
here is the fiddle http://jsfiddle.net/h2gfT/9/
one with jquery chaining hotness
$('.archive-item-list-pt li').each(function(i,j) {
var cls=$(this).children("a").text().toLowerCase().replace(' ','-');
$(this).addClass(cls);
});
Sort items in place based in the arbitrary key function
Sorting the entries with jQuery can be done in a couple diffrent ways, but if you just want to append CSS to each of them you could do that in two different ways.
$('li').each(function(l) { $(this).attr('class', '<insertnameofcssclasshere>') })
or
$('li').each(function(l) { $(this).css(<insertcssstuff here>) })
Of course, these would apply it to all li elements on your page. You would want to use more specific or contained selectors if you want to affect just some of them.