Chris Marasti-Georg
Chris Marasti-Georg

Reputation: 34700

How do I reapply a jQuery selector?

I have a javascript function that selects several elements, and then performs some DOM manipulation. When the DOM manipulation involves adding more elements that match the initial selectors, I'd like to re-apply them to include the new elements.

var row1 = table.find("tr.row1 td");
var row2 = table.find("tr.row2 td");
var row3 = table.find("tr.row3 td");

for(...) {
   if() {//Some condition is met
       table.children().each(function(row) {
          row.append(row.children().eq(5).clone());
       });
       row1.refresh(); // I'd like something here like refresh, rather than row1 = table.find("tr.row1 td");
    }
    //Code that uses row1, row2, and row3
}

Is there a function that does what I'm looking for on the refresh() line?

Upvotes: 4

Views: 1397

Answers (3)

Ansel Santosa
Ansel Santosa

Reputation: 8454

jQuery objects are essentially an Array of HTMLElements. Just push the new elements when you append them:

 row1.push(row.children().eq(5).clone().appendTo(row)[0]);

I didn't test this chain but I believe appendTo() will return the cloned jQuery object, [0] will return the corresponding HTMLElement

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075755

There isn't really a function that does what you've described, you just re-issue the original request.

If you have a jQuery object (like your row1), you can use this undocumented mechanism to re-run the original request:

row1 = $(row1.selector, row1.context);

...but again, the selector property is undocumented (context is documented) and so while it works now in 1.7.1, it may well not work in 1.7.2.

A better approach may be to only keep hold of the jQuery object for the rows as long as you're actually doing something with it, but it depends on the cost of re-acquiring the list and how frequently you do that.

Upvotes: 7

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

The initial selector that allowed to obtain the resultset is not stored, so you could reexecute this selector:

row1 = table.find("tr.row1 td");

Upvotes: 3

Related Questions