Reputation: 17049
I am using this for sorting text in elements:
$('div span')
.sort(function(a, b){
return ($(b).text()) < ($(a).text()) ? 1 : -1;
})
.appendTo('div');
It works good in cases as
<div>
<span>B</span>
<span>C</span>
<span>A</span>
</div>
But I need separate them with commas (they are already here before sorting):
<div>
<span>B</span>, <span>C</span>, <span>A</span>
</div>
I can't understand where I should use split
to separate them with commas.
Is it possible without doing everything from scratch? JQuery way.
Upvotes: 0
Views: 306
Reputation: 144699
You can use the after
method:
$('div span').sort(function (a, b) {
return ($(b).text()) < ($(a).text()) ? 1 : -1;
}).appendTo('div').not(':last').after(',');
edit: Working with textNodes can make your code unmaintainable, I would suggest wrapping the ,
textNodes with another element, then you can remove them easily without filtering element's textNodes or resetting innerHTML
of the wrapper element:
$('div span.comma').remove();
$('div span').sort(function (a, b) {
return ($(b).text()) < ($(a).text()) ? 1 : -1;
}).appendTo('div').not(':last').after('<span class="comma">,</span>');
This is one way of filtering textNodes that have ,
as their nodeValue
:
$('div').contents().filter(function() {
return this.nodeType === 3 && $.trim(this.nodeValue) === ','
}).remove();
Upvotes: 3