Manipulate table with jQuery
I am stuck working with a horrible application that has table driven layout. It is severely limiting and I can not add unique classes or really do anything to edit the html output. Can someone show me how I could possibly manipulate the layout using jQuery.
The code looks something like this:
<table width="100%" border="0" cellpadding="3" cellspacing="0">
<tr>
<td>
<TABLE CELLPADDING="3" CELLSPACING="" BORDER="0">
<TR>
<TD>
<TABLE CELLPADDING="3" CELLSPACING="0" BORDER="0">
<TR>
<TD STYLE="padding:3px;">
<TABLE CELLPADDING="0" CELLSPACING="0" BORDER="0">
<TD NOWRAP CLASS="MainNavigation">
Link 1</TD>
开发者_StackOverflow中文版 </TABLE>
</TD>
<TD STYLE="padding:3px;">
<TABLE CELLPADDING="0" CELLSPACING="0" BORDER="0">
<TD NOWRAP CLASS="MainNavigation">
Link 2</TD>
</TABLE>
</TD>
<TD STYLE="padding:3px;">
<TABLE CELLPADDING="0" CELLSPACING="0" BORDER="0">
<TD NOWRAP CLASS="MainNavigation">
Link 3</TD>
</TABLE>
</TD>
</TR>
</TABLE>
<TABLE CELLPADDING="3" CELLSPACING="0" BORDER="0" >
<TR>
<TD STYLE="padding:3px;">
<TABLE CELLPADDING="0" CELLSPACING="0" BORDER="0">
<TD NOWRAP CLASS="MainNavigation">
Link 4</TD>
</TABLE>
</TD>
<TD STYLE="padding:3px;">
<TABLE CELLPADDING="0" CELLSPACING="0" BORDER="0">
<TD NOWRAP CLASS="MainNavigation">
Link 5</TD>
</TABLE>
</TD>
</TR>
</TABLE>
</TD>
</TR>
</TABLE>
</td>
</tr>
</table>
Ugly right?!
So from this example how could I manipulate it with scripts to move Link 3 into the second table? I started a fiddle with this here :
http://jsfiddle.net/2gYfq/
Lucky for us, jQuery has ways to easily deal with such ugliness. Using :contains()
, .detach()
, and insertBefore()
you can:
var refTD = $('.MainNavigation:contains("Link 4")').parent().closest('td');
$('.MainNavigation:contains("Link 3")').parent().closest('td')
.detach()
.insertBefore(refTD);
See example →
精彩评论