views:

184

answers:

1

Hi all I am trying to insert a block element Insert something before another . I am not sure if I am using the right method but here is my code. Hope you guys can help. Thanks!

Jquery

$("#addMatch").click(function(){

    $("<td>New insert</td>").insertBefore("#addMatch").closest('tr');

    return false;   //this would insert the <td>New insert</td> before the               
                    //<td><input type="button" id="addMatch" name="addMatch" value="Add 
                    //Match" </td> but not <tr>
});

Html

<tr>
<td>some data</td>
</tr>

//can't tell how many tr would show before the last "addMatch" button. It's dynamic. 
// I want the <td>New insert</td> show up here.
    <tr> 
    <td><input type="button" id="addMatch" name="addMatch" value="Add Match" </td>
    </tr>
+5  A: 

<td> should always be in a <tr>.

I would probably make your function like this:

$("#addMatch").click(function(){
    $(this).parents('tr:first').before('<tr><td>New Insert</td></tr>');
    return false;
});
Kerry
Instead of `.parents('tr:first')`, there's `.closest('tr')` :)
Nick Craver
is .closest faster?
Kerry
Good one. Thanks! Yes, I think the closest is faster.
Jerry
Good to know -- though curious on the logic behind it. closest has to check both parents and children, right? Parents only checks parents, and they both stop on the first one, is it just because of the way jQuery does it?
Kerry