Most succint way to refer to a newly created object in jQuery?

I have a function called by clicking a link in TD. After clicking, I go back to the DOM in the TR that the link is inside, and then create a new TR after it.

So far so good.

Now that I have created this new TR, with a TD inside, what is best about this newly created TD. Or do I have to walk my way back to 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;
});

      

+2


source to share


2 answers


$("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 replace parents

with closest

if you update one tr. An alternative but more manual way would be to do ...$(this).parents('tr').next().find('td')

+1


source


insertAfter (). wrap () is handy 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 concatenation operator. "& Amp;" used for integers to calculate bitwise AND.

0


source







All Articles