views:

61

answers:

2

I have a function called on the click of a link within a TD. Upon clicking, I traverse back up the DOM to the TR that the link was within, then create a new TR after it.

So far so good.

Now that I've created that new TR, with a TD within, what's the best to now refer to that newly created TD. Or, do I need to traverse my way back into the new TD I created back from the original clicked object?

$("td.expandable a").click(function(){
 // figure out the number of columns we need to span
 var colspan;
 colspan = $(this).parents("tr").children("td").size();

 // insert the new TR
 $(this).parents("tr").after("<tr><td colspan=' & colspan & '></td></tr>");

 // **what syntax would I use here to refer to the above made TD?**

 return false;
});
+1  A: 
$("td.expandable a").click(function(){
        // figure out the number of columns we need to span
        var colspan = $(this).parents("tr").children("td").size(),
            tr = $("<tr><td colspan=' & colspan & '></td></tr>");

        // insert the new TR
        $(this).parents("tr").after(tr);

        // **what syntax would I use here to refer to the above made TD?**
        tr.find('td')

        return false;
});

You can also probably substitute parents with closest if you're updating one tr. An alternative yet more manual way would have been to do... $(this).parents('tr').next().find('td')

meder
Wouldn't tr.find('td') batch all instances of that newly created TR? In my case, we might me inserting a bunch of these and would want to match only the one I just created. I may be misunderstanding 'parents'. Is that returning the parent TR or all parent TRs of the object as an array? If the latter, I think I need closest instead.
DA
ah, indeed...I need to use 'closest' rather than 'parents' as I only one the single parent.Also, on second read, I now realize that 'tr' isn't a string, but an actual jquery object, so that, indeed, will match that specific one. Thanks meder!
DA
A: 

insertAfter().wrap() are convenient for this type of thing:

$('td.expandable a').click(function() {
    var $parent = $(this).parents('tr');
    var colCount = $parent.children('td').size();
    var $td = $('<td colspan=' + colCount + '></td>');
    $td.insertAfter($parent).wrap('<tr></tr>');
    return false;
});

I used the string concatentation operator "+". "&" is used for integers to calculate bitwise AND.

Keith Morgan