I'd like to change table cell position using jQuery. String could vary.
A | string
B | string
C | string
string | A
string | B
string | C
string | A
string | B
string | C
A | string
string | A
string | A
B | string
string | B
string | B
C | string
string | C
string | C
<table>
<tr>
<td>A | string</td>
</tr>
<tr>
<td>B | string</td>
</tr>
<tr>
<td>C | string</td>
</tr>
<tr>
<td>string | A</td>
</tr>
<tr>
<td>string | B</td>
</tr>
<tr>
<td>string | C</td>
</tr>
<tr>
<td>string | A</td>
</tr>
<tr>
<td>string | B</td>
</tr>
<tr>
<td>string | C</td>
</tr>
</table>
I made it with sources below, but it's not practical because other cells like 'D', 'E', etc. can be added in the future.
$("tr:contains(' | A')").insertAfter("tr:contains('A | ')");
$("tr:contains(' | B')").insertAfter("tr:contains('B | ')");
$("tr:contains(' | C')").insertAfter("tr:contains('C | ')");
You can do it dynamicly like this
$('table').find('tr').each(function(){ var text = $(this).find('td').first().text(); var match = (text.match(/^[AZ] \\|/)) if(match){ $("tr:contains(' | " + match[0][0] + "')").insertAfter("tr:contains('" + match[0] + " ')"); } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td>A | string</td> </tr> <tr> <td>B | string</td> </tr> <tr> <td>C | string</td> </tr> <tr> <td>string | A</td> </tr> <tr> <td>string | B</td> </tr> <tr> <td>string | C</td> </tr> <tr> <td>string | A</td> </tr> <tr> <td>string | B</td> </tr> <tr> <td>string | C</td> </tr> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.