Hallemon
Hallemon

Reputation: 171

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"));

Upvotes: 1

Views: 757

Answers (2)

stovroz
stovroz

Reputation: 7095

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")

Upvotes: 2

CumminUp07
CumminUp07

Reputation: 1978

Yes you can use the clone just like a regular jQuery selector. For your example it would be

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

or even

console.log(grid.find("td"));

Upvotes: 1

Related Questions