开发者

How do I search and remove/append a row in Jquery or Javascript?

If I have a table

<table id="myTable"><tr><td>First Thing</td><td>First Value</td></tr>
<tr><td>Second Thing</td><td>Second Value</td></tr>
<tr><td>Th开发者_开发百科ird Thing</td><td>Third Value</td></tr>
</table>

How can I use JQuery or javascript to search to get the index of the row with text "Second Value" and remove it? Also is it possible to create a new row

<tr><td>Fourth Thing</td><td>Fourth Value</td></tr>

with the click of a button? Will I have to iterate through the existing rows to get the last index of the row to insert it in?


You can achieve this easily using the :contains() selector, the remove() function, and the append() function. You don't need to iterate through the rows to find what you're looking for.


To get the index:

$("#myTable").find("td:contains('Second Value')").parent().index();

To remove it:

$("#myTable").find("td:contains('Second Value')").parent().remove();

To add a row:

$("#myTable").append("<tr><td>Fourth Thing</td><td>Fourth Value</td></tr>");

working example: http://jsfiddle.net/hunter/PzJWC/


You should ideally generate id's per each tr/td - but thats if you getting data dynamically i suppose.

If you know the order of your tables then you can use these sleectors from jQuery

$('tr:last-child').html('<p>This is the absolouty last tr in the WHOLE page<p>')

$('tr:nth-child(even)').addClass('evenColors')

$('tr:nth-child(4n)').remove()  //Removes the 4th from the top TR DOM Element

var theValueOf = $('tr:first-child').html() //assigns the innerHtml to your var

So if you have 10 tables each table should have an id or class

 <table id="table1"> ...bla... </table>

$('table1 tr:last-child').remove() //Remove last TR from Table1

You will need to structure your html more with id's and classes

In your case you will have to restructure your table some how programatically to atach unique ids to each row then use jquery to select it. This is ideal world But you do a loop and check each inner html until what you want and do a .remove()

But to get the INDEX use hunters reply! But from experience this is a headache on large and dynamic documents.


JQuery has .insertAfter and insertBefore. For targeting you can also use nth-child css selector or if you want it dynamic (like insert a row after the row they click) you can use the 'this' operator and some dom navigation. All that said be very careful when editing tables on the fly, they have some peculiarities about where things can be inserted and are heavy on performance.


i just did it ;) to add row (you may not want to use append because your table may have tbody etc):

$('#myTable tr:last').after('<tr id="forth_row"><td>forth thing</td><td>forth value</td></tr>');}

to find and remove that row:

$('#myTable').find("#forth_row").remove();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜