Search code examples
javascriptjquerydomclone

Find element within a jQuery clone


I'm working on an app where I need to clone a table, then access the td and tr independently, depinding on their attributes or classes within this table.

Is there an easy way to accomplish this with the classical jQuery selector or do I need to write a whole new function ?

Code :

JS

var grid = $("table").clone();
console.log($(grid).$("td"));

Solution

  • Assuming you're starting with just one table, the following selector string will find all the rows in that table (as you know).

    $("table tr")
    

    but if you're referencing your table with a variable you have to use the find operator with the remainder of the original selector string instead, e.g.

    var $table = $("table");
    $table.find("tr")
    

    I'm prefixing my variable with a $ as a note-to-self that it's already a jQuery object, i.e. there's no need to $($table).

    You can work with the clone in exactly the same way:

    var $clone = $("table").clone();
    $clone.find("tr")