0

Here is code from HTML. I would like to sort everything by class or src. I've been searching for answers a very long time and seems like i wont find that answer i need. Halp?

<table border="0" cellpadding="0" cellspacing="0" width="500">
<tbody>
<tr>
<td>
<img src="/images/gold.gif" class="a1">
<img src="/images/silver.gif" class="a2">
<img src="/images/copper.gif" class="a3">
<img src="/images/gold.gif" class="a1">
<img src="/images/silver.gif" class="a2">
<img src="/images/copper.gif" class="a3">
<img src="/images/gold.gif" class="a1">
<img src="/images/silver.gif" class="a2">
<img src="/images/copper.gif" class="a3">
</td>
</tr>
</tbody>
</table>

How do i sort those images so it would look something like this...

<img src="/images/gold.gif" class="a1">
<img src="/images/gold.gif" class="a1">
<img src="/images/gold.gif" class="a1">
<img src="/images/silver.gif" class="a2">
<img src="/images/silver.gif" class="a2">
<img src="/images/silver.gif" class="a2">
<img src="/images/copper.gif" class="a3">
<img src="/images/copper.gif" class="a3">
<img src="/images/copper.gif" class="a3">
  • 3
    What answers have you found that you could not apply to your problem? Have you tried any code? – Bergi Jan 23 '14 at 23:00

1 Answers1

1

This 3-liner will do it:

$("img").sort(function(a,b) {
   return (a.className>b.className)-(b.className>a.className);
}).appendTo("td");

(demo at jsfiddle.net)

How sorting elements does work:

  1. Get them in a collection. $("img") does select them in your example
  2. .sort them, in your case by their className property. See Sort array of objects by string property value in JavaScript and other sort-by-X questions as a reference.
  3. Re-append them to the document in their new order - in your case the parent td. They are getting removed from their old position automatically.

You probably will need to adapt the selectors and use something more specific.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Whoa! Nice! But it has conflict with the form below. Here is picture of that conflict... http://puu.sh/6w6db.png – user3229858 Jan 24 '14 at 06:14
  • I cam't see a conflict on a picture, and without the markup I can't really help you with the code. – Bergi Jan 24 '14 at 08:01
  • http://puu.sh/6wcc2.7z <- Here is that original HTML file with folder full of images. That part starts from line nr. 297 and looks like it has conflicts with almost everything. See that bar up there? It drags those icons to the bottom, as you see in this picture http://puu.sh/6w6db.png – user3229858 Jan 24 '14 at 09:10
  • Just use some kind of `var td = $(YOUR_SELECTOR_HERE); td.find("img").….appendTo(td);` – Bergi Jan 24 '14 at 10:01